我希望能够在不影响UI变化的情况下阻止主线程上的代码执行。
我尝试着给出一个简化的示例来展示我的需求,但是这可能并不能完全表达我的意思,否则我也不会发布这个问题了。我只是希望这段代码能够为我的问题提供一些背景信息。
在表单的按钮点击处理程序中,我有以下代码:
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()上没有设置超时时间,那么在Invoke()调用时应用程序将会死锁。
至于为什么我想这样做,我被要求将一个应用程序的一个子系统移动到后台线程中进行工作,但仍然只有在某些情况下和与该子系统相关的特定工作时才阻止用户的工作流程(主线程)。