Solved

Difference between [MethodImpl(MethodImplOptions.Synchronized)] and lock(this)

Posted on 2004-03-22
13
7,281 Views
Last Modified: 2007-12-19
I was searching for a C# counterpart for the Java "synchronized" keyword and I found that there is an Attribute "[MethodImpl(MethodImplOptions.Synchronized)]".
There are quite a lot of synchronization attributes in C# which is rather confusing.

What is the difference between:

public void MyMethod()
{
    lock(this)
    {
        ...
    }
}

and this:

[MethodImpl(MethodImplOptions.Synchronized)]
public void MyMethod()
{
    ...
}
0
Comment
Question by:ptmcomp
  • 6
  • 4
  • 2
  • +1
13 Comments
 
LVL 20

Assisted Solution

by:TheAvenger
TheAvenger earned 250 total points
ID: 10648266
MethodImplOptions.Synchronized: Specifies the method can be executed by only one thread at a time.

The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock

So: if you lock an object, all other threads that need to access THIS PARTICULAR OBJECT will wait, until the other object finishes. However if you mark a method as Synchronized, THIS PARTICULAR METHOD will not be executed at more than one thread. Lock secures the object, Synchronized secures the method
0
 
LVL 10

Author Comment

by:ptmcomp
ID: 10648359
Ok so [MethodImpl(MethodImplOptions.Synchronized)] does the same as the code below?

private static object myMethodLockRoot = new object();
public void MyMethod()
{
   lock(myMethodLockRoot)
   {
       ...
   }
}
0
 
LVL 20

Expert Comment

by:TheAvenger
ID: 10648376
if you use the myMethodLockRoot  object only for this, yes
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
LVL 10

Author Comment

by:ptmcomp
ID: 10651490
If I translate this Java code:

public synchronized void myMethod() {
    ....
}

Shall I use the Attribute or an explicit lock?



PS: @TheAvenger: I'll give you the points but I don't want to close the question yet, I will raise the points and split them if I get more input about differences in IL-Code or other background information.
0
 
LVL 22

Expert Comment

by:_TAD_
ID: 10651580


** Not for points **

I think Avenger has pretty much nailed it right on the head.  It really comes down to locking an object or a method (more or less).

If the object exists ONLY inside of a single method pretty much either code does the exact same thing.

In your particular case

   <Java>
   public synchronized void myMethod() {
    ....
   }

You'll want to use the attribute method of synchronizing.
0
 
LVL 22

Accepted Solution

by:
_TAD_ earned 100 total points
ID: 10651615


again....

** Not for Points **


My Java is a bit rusty, but here goes....


<JAVA>
public synchronized void myMethod() {
    ....
 }

                         -- Same as --

<C#>
[MethodImpl(MethodImplOptions.Synchronized)]
public void MyMethod()
{
    ...
}





<JAVA>
public void myMethod() {
    StringWriter swr = new StringWriter(<Params>);
    Synchronized(swr){
        ...
    }
 }

            --- Same As ---

<C#>
public void myMethod() {
    StreamWriter swr = new StreamWriter(<params>);
    lock(swr){
        ...
    }
 }
0
 
LVL 20

Expert Comment

by:TheAvenger
ID: 10651709
Can't add anything more to _TAD_: said all
0
 
LVL 10

Author Comment

by:ptmcomp
ID: 10655762
Ok guys, thanks a lot!
0
 
LVL 10

Author Comment

by:ptmcomp
ID: 10655774
Weird! - How does EE determine which is the "accepted" and which is the "assisted" answer?? Anyway it was meant to be other way around and the points should be 250 for TheAvenger and 100 for _TAD_ both with grade A.
0
 
LVL 20

Expert Comment

by:TheAvenger
ID: 10655795
The grade is A and I got 1000 points (4 x 250) so I think only the remarks here are wrong....
0
 
LVL 10

Author Comment

by:ptmcomp
ID: 10659740
Just had a look at my Java book it says synchronize locks "this" which would mean:

<JAVA>
public synchronized void myMethod() {
    ....
 }
                         -- Same as --

<C#>
public void MyMethod()
{
    lock(this)
    {
    ...
    }
}

Anyway I think I won't use the Attribute since it's harder to understand.
0
 
LVL 2

Expert Comment

by:mjwills
ID: 10992904
TheAvenger,

<quote>
MethodImplOptions.Synchronized: Specifies the method can be executed by only one thread at a time.

The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock

So: if you lock an object, all other threads that need to access THIS PARTICULAR OBJECT will wait, until the other object finishes. However if you mark a method as Synchronized, THIS PARTICULAR METHOD will not be executed at more than one thread. Lock secures the object, Synchronized secures the method
</quote>

Incorrect. Both lock(this) and MethodImplOptions.Synchronized do the same thing - they lock against the object. This is why MethodImplOptions.Synchronized should be avoided. See http://www.dotnet247.com/247reference/msgs/45/225597.aspx (for example).

Seeya
Matthew
0
 
LVL 10

Author Comment

by:ptmcomp
ID: 10993743
Thanks for the hint. I think I'll stick to the explicit locks since I know what they do and don't change behaviour in further versions.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

789 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question