how to create a locked method

  • Thread starter Thread starter Saper\(ek\)
  • Start date Start date
S

Saper\(ek\)

in java I could write a synchronized method like this
public synchronized MyMethod()
{
blablabla
}

how (and if) can I do this in C#?

--


"Zeglarstwo jest koniecznoscia
zycie nia nie jest"

www.saper.infra.pl/

Saper(ek)
 
Saper(ek) said:
in java I could write a synchronized method like this
public synchronized MyMethod()
{
blablabla
}

how (and if) can I do this in C#?


Look at "lock" keyword.
 
Or, you can just attribute the method like this:

[MethodImpl(MethodImplOptions.Synchronized)]
public MyMethod()

This is closer to the sycnhronized keyword when applied to a method.
The lock keyword should be used like the synchronized keyword in Java when
applying to code in a method.

Hope this helps.
 
i know I can lock objects
lock(object)
{
blablabla;
}
but can I lock a method?

in java there are 2 posibilities...

synchronized(object)
{
blablabla;
}

and

public synchronized void MyMethod()
{
blablabla
}

I ask again then. can I lock a method ic C#


"Zeglarstwo jest koniecznoscia
zycie nia nie jest"

www.saper.infra.pl/

Saper(ek)
 
Saper(ek) said:
i know I can lock objects
lock(object)
{
blablabla;
}
but can I lock a method?

in java there are 2 posibilities...

synchronized(object)
{
blablabla;
}

and

public synchronized void MyMethod()
{
blablabla
}

I ask again then. can I lock a method ic C#

Nicholas has showed you how you can do it - but here's why you
shouldn't (and why you shouldn't use synchronized methods in Java):

It's almost always worth synchronizing on a reference which *isn't*
available to other classes, unless you're *explicitly* making it
available for precisely that purpose. Otherwise, other classes may
decide to lock on that reference and you could end up with a deadlock
which could be very hard to debug.

Instead, use things like:

// At the class level
object resourceLock = new object();

then within a method you can use:

lock (resourceLock)
{
....
}

That also makes the code more self-documenting, particularly if you end
up using multiple locks to allow finer-grained access.
 
One other point on this

By using "lock", you may be able to reduce the number of lines of code for
which the lock is held. If you lock for the method, the lock covers all the
lines in that method.

--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://blogs.gotdotnet.com/ericgu/

This posting is provided "AS IS" with no warranties, and confers no rights.
 
Back
Top