Solved

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

Posted on 2004-03-22
13
7,183 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
 
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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

747 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now