【发布时间】:2014-03-27 21:56:48
【问题描述】:
我使用并行任务库在后台运行异步任务。有时我必须等待后台任务的完成委托,而 UI 线程是非阻塞的。
所以:
- 在 UI 线程中启动微调器
- 在后台做一些需要等待的工作
- 然后运行另一个后台任务
- 在 UI 中停止微调器
我在UI线程(2)中启动了后台任务,之后我尝试调用Wait方法,这导致了死锁......
我需要一个解决方案来等待指定的后台任务而不阻塞 UI 线程。 .NET 框架是 4,所以我不能使用 async 和 await
更新:
在 UI 线程中:
Task task = Task.Factory.StartNew<T>(() => BackgroundTask());
task.ContinueWith(task => CompletedTask(((Task<T>)task).Result); // I want to prevent later tasks to start before this task is finished
task.Wait(); // this will block the ui...
任何建议表示赞赏。
【问题讨论】:
-
您使用的是 Visual Studio 2012 或更高版本吗?如果是这样,您可以使用包
Microsoft.Bcl.Async在 .NET 4.0 中启用 async/await -
不幸的是 VS 2010
-
使用 Stephen Toub 的
Then或Iterate模式。更多详情:stackoverflow.com/a/22291625/1768303
标签: c# asynchronous task-parallel-library