c#中是否存在类似于lock {}的构造,但在从事件处理程序调用时工作,即在处理后续事件之前等待代码块完成。C#从事件中锁定
我遇到的问题是锁只阻止其他线程获取对象上的锁,但是如果同一线程上的事件处理程序被调用,锁块内代码的执行将被中断,并且在返回执行原始代码之前处理新事件。
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
}
}
线程不能被事件“中断”。你还没有诊断出真正的问题。 – 2011-04-05 20:06:08
确实 - 你是对的 - 我没有诊断出真正的问题。 – 2011-04-05 20:47:57