我使用并行任务库在后台运行异步任务。有时,当UI线程未阻塞时,我不得不等待后台任务的完成委托。
所以:
在UI线程(2)中启动后台任务之后,我尝试调用等待方法,这会导致死锁.
我需要一个解决方案来等待指定的后台任务,而不阻塞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...任何建议都很感激。
发布于 2014-03-27 13:49:56
您可以使用ContinueWith将一个延续附加到任务,并在任务完成时运行一些代码。await实际上也在幕后做着同样的事情。
当所有的任务集合完成后,您可以使用Task.Factory.ContinueWhenAll运行一个延续。
您可以从UI线程中使用TaskScheduler.FromCurrentSynchronizationContext()来获得能够在UI线程中调度任务的任务调度程序。
https://stackoverflow.com/questions/22689511
复制相似问题