Is there a construct in c# that is like lock { }, but works when called from an event handler i.e. waits for the code block to complete before handling a subsequent event.
The problem I am having is that lock { } only prevents other threads from obtaining a lock on the object, but if an event handler on the same thread is called, the execution of code within the lock block is interrupted, and the new event is handled before returning to the execution of the original code.
object DoStuffLock = new object(); public void DoStuff() { lock (DoStuffLock) { // Do stuff that we don't want to be interrupted, // but because it is called from an event handler // it still can be interrupted despite the lock } } I am currently working around the problem like this (but it is hardly ideal):
object DoStuffLock = new object(); // this gets called from an event, and therefore can be interrupted, // locking does not help, so launch separate thread public void DoStuff() { var x = new Thread(DoStuffInternal); x.Start(); } private void DoStuffInternal() { lock (DoStuffLock) { // Do stuff that we don't want to be interrupted } }