线程:应用程序在使用 Thread.Join() 后冻结

Threading: Application Freezes after using Thread.Join()

我知道 .Join() 会导致线程暂停并等待线程完成其工作,但是如何避免 UI 被冻结?这就是我的代码的样子

Thread dataThread = new Thread(()=> data = getData(id));
dataThread.Start();
dataThread.Join();

Thread storingThread = new Thread(()=> storeData(data));
storingThread.Start();

我需要从第一个线程开始加入 returns 一个包含需要通过第二个线程存储的数据的对象。但这会导致 UI 冻结。我怎样才能在后台线程中实现这些?你们认为我应该改变什么?

看来你不需要两个线程:

Thread dataThread = new Thread(() => storeData(getData(id)));
dataThread.Start();

请注意,Task 优于 Thread。另外,您可能应该使用 await。

如果您使用的是 .Net framework >= 4.5,您可以使用 Tasks

await Task.Run(() => data = getData(id));
await Task.Run(() => storeData(data));

或在一个命令中

await Task.Run(() => storeData(getData(id)));

如果你不必等到它完成你也可以这样做:

Task.Run(() => storeData(getData(id)));

将所有工作放在一个线程中,这样 UI 就不会停止:

 ThreadPool.QueueUserWorkItem( () => storeData(getData(id)));

或 .Net 4

Task.Factory.StartNew(() => storeData(getData(id)));

使用 async / await 关键字。小示例代码:

private async void Method()
{
     var result = await ExecuteAsync();
     // result == true 
}

private async Task<bool> ExecuteAsync()
{
     //run long running action
     return true;
}

在 .net 4.0 中,您需要安装 Microsoft.Bcl.Async 才能使用此功能。

可以在 http://blog.stephencleary.com/2012/02/async-and-await.html

上阅读有关此功能的精彩介绍

答案已经给出。作为额外的,我给了我。

您也可以这样使用 ContinueWith:

Task<string>.Factory.StartNew(() => "Hey!").ContinueWith(t => Console.WriteLine(t.Result));