Gug*_*dze 2 c# user-interface multithreading sleep freeze
我试着尝试一下Thread.Sleep().我用一个按钮创建了基本的Windows窗体应用程序.
private void button1_Click(object sender, EventArgs e)
{
Thread thread1 = new Thread(DoStuff);
thread1.Start();
for (int i = 0; i < 100000; i++)
{
Thread.Sleep(500);
button1.Text +=".";
}
}
public void DoStuff()
{
//DoStuff
}
Run Code Online (Sandbox Code Playgroud)
当我单击我的按钮时,该DoStuff方法工作正常,但GUI冻结,没有任何反应.有人能解释一下为什么吗?
Thread.Sleep只是睡眠当前线程(即阻止它做任何事情,例如重绘,处理点击等),在你的情况下是UI线程.如果你把它Sleep放在DoStuff你不会遇到块,因为你将在一个单独的线程,虽然你将无法更新button1.根据您使用的.NET版本考虑使用任务并行库,如下所示:
private TaskScheduler _uiScheduler;
public Form1()
{
InitializeComponent();
_uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
}
private void button1_Click(object sender, EventArgs e)
{
Thread thread1 = new Thread(DoStuff);
thread1.Start();
// Create a task on a new thread.
Task.Factory.StartNew(() =>
{
for (int i = 0; i < 100000; i++)
{
Thread.Sleep(500);
// Create a new task on the UI thread to update the button
Task.Factory.StartNew(() =>
{ button1.Text += "."; }, CancellationToken.None, TaskCreationOptions.None, _uiScheduler);
}
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2691 次 |
| 最近记录: |