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