开发者

c# threads synchronisation

I need to use lock obj开发者_C百科ect, but it is already used by another thread. I wish to wait while the lock object will be free but have no idea how to do this.

I found sth like:

if(Monitor.TryEnter(_lock)
{
try
{
    // do work
}
finally
{
    Monitor.Exit(_lock);
}

}

But I it just check and go on, but I wish to wait until lock object is free.


Either use this:

Monitor.Enter(_lock)

try
{
    // do work
}
finally
{
    Monitor.Exit(_lock);
}

or - more preferably - the lock keyword:

lock(_lock)
{
    // do work
}

In fact, those code snippets will generate the same code. The compiler will translate the second code into the first one. However, the second one is preferred because it is far more readable.

UPDATE:
The lock belongs to the thread it was acquired in. That means, nested usage of the lock statement is possible:

void MethodA()
{
    lock(_lock)
    {
        // ...
        MethodB();
    }
}

void MethodB()
{
    lock(_lock)
    {
        // ...
    }
}

The above code will not block.


You can use Monitor.Enter

From docs:

Use Enter to acquire the Monitor on the object passed as the parameter. If another thread has executed an Enter on the object but has not yet executed the corresponding Exit, the current thread will block until the other thread releases the object.


I agree with @Daniel Hilgarth, the lock syntax is preferred.

Regarding your question:

I wish to wait while the lock object will be free but have no idea how to do this.

As per the MSDN description:

lock ensures that one thread does not enter a critical section while another thread is in the critical section of code. If another thread attempts to enter a locked code, it will wait (block) until the object is released.

i.e. the code you have already does what you want it to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜