Solved

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

Posted on 2004-03-22
13
7,356 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

 
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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
This video shows how to use Hyena, from SystemTools Software, to update 100 user accounts from an external text file. View in 1080p for best video quality.

738 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