how to create a locked method

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)
 
G

Girish Bharadwaj

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.
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 
S

Saper\(ek\)

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)
 
J

Jon Skeet [C# MVP]

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.
 
E

Eric Gunnerson [MS]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top