【发布时间】:2010-09-26 12:33:52
【问题描述】:
我想以其他方式阻止主线程上的代码执行,同时仍允许显示 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() 调用上死锁。
至于我为什么要这样做,我的任务是移动应用程序的一个子系统以在后台线程中工作,但它仍然只有时会阻塞用户的工作流(主线程)仅与该子系统相关的某些类型的工作。
【问题讨论】:
标签: c# multithreading