C# 中是否有类似于 lock { } 的构造,但在从事件处理程序调用时起作用,即在处理后续事件之前等待代码块完成。
我遇到的问题是 lock { } 仅阻止其他线程获取该对象的锁,但是如果调用同一线程上的事件处理程序,则锁 block 内代码的执行将被中断,并且在返回到原始代码的执行之前处理新事件。
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
}
}
我目前正在解决这样的问题(但这并不理想):
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
}
}
最佳答案
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
这真的不可能发生。如果您的线程正在执行,则事件不能在同一个线程上发生 - 它必须在不同的线程上引发。
话虽如此,您的“第二种方法”在很多方面都更胜一筹。有一个隐含的假设,即事件处理程序将很快返回。 “阻塞”事件处理程序通常是设计不良的标志,并且可能会导致问题,特别是因为事件发布者不会期望事件被阻塞。
关于C# 事件锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5557400/