Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2004-03-22
13
Medium Priority
?
7,528 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 1000 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
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!

 
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 400 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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
Suggested Courses

715 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