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.