How to use lock()
11.10.2006 Среда 22:59
Software: .Net, C#
If you have to synchronize execution of a piece of your code, and framework executing your code can be creating several instances of the class that contains your code, then this will not work:
lock(this)
It will not work because it only synchronizes threads executing on the same instance of the class. Threads executing on different instances will continue to run simultaneously creating you all kinds of problems. To avoid this behaviour use lock on a static member of the class:
class MyClass
{
private static object lockObject = new object();
...
public void foo()
{
lock(lockObject)
{
}
}
}
This will ensure all threads executing you code are synchronized, regardless of how many instances of your class framework creates, because static class members are shared by all instances of that class.
I faced this problem while writing code for a custom FILE adapter for a BizTalk project. At that time I used lock(this)
. Stress testing on large amount of data revealed symptoms usual for situations when threads interrupt each other. At the same time, testing on small amounts of data did not show these issues.
Investigation revealed the cause: BizTalk engine was creating multiple threads running on multiple instances of the class used in the FILE adapter when amount of data being processed was large enough. When small amount of data was used, BizTalk only created one instance. I am curious as to why BizTalk creates several instances of the class even with multiple threads. Why not run all threads on the same instance? But may be I lack some knowledge of multi-threading here.