Pergunta

I have a multithread running context. I want one resource (let's say Object r) to be mutual exclusive. Can I use the resource itself as its monitor object?

e.g.

    lock(r)
    {
        // do something...
    }
Foi útil?

Solução

If r stays the same object throughout - for example, r is a List that you're adding items to from several threads:

lock (r)
{
    r.Add("Hello world");
}

then this is fine - it doesn't cause any issues, and you can read it as you're specifically "locking r". (Just make sure you put a similar lock around any other code that's using r too.)

However, if r is being switched for another object inside the lock:

lock (r)
{
    r = new List<string>();
}

this isn't a good idea, because you could end up with two threads running the lock against two different versions of r. In this case, you should create an unchanging object specifically to lock against - you're more "locking the code block" than "locking r".

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top