开发者

What object should a Monitor wait on?

When using Monitor.Wait(object obj) what should one use for the obj? In this article I'm reading on multithreading in .NET the author instantiates a new Object() to be used only as a monitor lock. Is this what you should do in practice, or is it more typica开发者_运维技巧l to Monitor the actual variable shared between two or more threads?


Yes, I normally lock on a new object created specially for that purpose. I also make sure that it is private and static and not a Type object. It's also important to realize that you're not really "locking" a variable or object, but using the lock as a token that prevents execution of a block of code on multiple threads.

Locking on this (the current instance if you're using C#) is less preferred because any code that has access to the instance could put a lock on it, increasing the chance of a deadlock. By creating your own lock object, you put yourself in complete control.

Here's an informative article on locking that explains the reasoning behind some of this.


It's also not good to lock on string objects because they are sometimes shared across app-domains like Type objects. Doing so could cause unnecessary contention if you had more than one app-domain.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜