我想在主線程上阻止代碼執行,同時仍然允許顯示UI更改。在C#中,等待mainthread,同時繼續處理UI更新? (.NET 2.0 CF)
我試圖想出我想要做的簡化示例版本;這是我能想到的最好的。顯然,它不表明我想要的行爲,或者我不會發布這個問題。我只是希望它給出了一些代碼上下文來支持我希望解決的問題的糟糕解釋。
在窗體上的按鈕單擊處理我有這樣的:
private void button2_Click(object sender, EventArgs e)
{
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
new Thread(delegate()
{
// do something that takes a while.
Thread.Sleep(1000);
// Update UI w/BeginInvoke
this.BeginInvoke(new ThreadStart(
delegate() {
this.Text = "Working... 1";
this.Refresh();
Thread.Sleep(1000); // gimme a chance to see the new text
}));
// do something else that takes a while.
Thread.Sleep(1000);
// Update UI w/Invoke
this.Invoke(new ThreadStart(
delegate() {
this.Text = "Working... 2";
this.Refresh();
Thread.Sleep(1000); // gimme a chance to see the new text
}));
// do something else that takes a while.
Thread.Sleep(1000);
autoResetEvent.Set();
}).Start();
// I want the UI to update during this 4 seconds, even though I'm
// blocking the mainthread
if (autoResetEvent.WaitOne(4000, false))
{
this.Text = "Event Signalled";
}
else
{
this.Text = "Event Wait Timeout";
}
Thread.Sleep(1000); // gimme a chance to see the new text
this.Refresh();
}
如果我沒有設置對WaitOne的一個timout()的應用程序將死鎖的調用()調用。
至於爲什麼我要做到這一點,我一直在負責移動應用程序做的工作在後臺線程中的一個子系統,但仍然有它阻止用戶的工作流程(主線程)僅有時和僅與該子系統有關的某些類型的工作。
就你所說的改變應用程序結構而言,它不完全是我的應用程序;那艘船已經駛了。 – CrashCodes 2008-12-11 20:46:39
至於爲什麼我想這樣做,我的任務是移動應用程序的一個子系統在後臺線程中執行工作,但仍然有時會阻止用戶的工作流程(主線程),並且對於某些類型工作的。 – CrashCodes 2008-12-11 20:49:41
@CrashCodes:太模糊,對不起; '有時'和'某些類型'可能意味着什麼 - 你將如何控制時間和內容? – 2008-12-11 20:52:41