异步等待块主界面 [英] Async wait block Main UI
问题描述
我正在使用新的异步等待功能从C#中的backgroundworker升级.在下面的代码中,我尝试使用ContinueWith方法复制多个任务的执行.
I am using the new async await features to upgrade from backgroundworker in C#. In the following code I am trying to replicate the execution of multiple tasks with ContinueWith method.
Task t1 = new Task
(
() =>
{
Thread.Sleep(10000);
// make the Task throw an exception
MessageBox.Show("This is T1");
}
);
Task t2 = t1.ContinueWith
(
(predecessorTask) =>
{
if (predecessorTask.Exception != null)
{
MessageBox.Show("Predecessor Exception within Continuation");
return;
}
Thread.Sleep(1000);
MessageBox.Show("This is Continuation");
},
TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.OnlyOnRanToCompletion
);
t1.Start();
try
{
t1.Wait(); <------ Comment
t2.Wait(); <------ Comment
}
catch (AggregateException ex)
{
MessageBox.Show(ex.InnerException.Message);
}
我的问题是,当我评论t1.wait和t2.wait时,任务未阻止UI.但是,当我取消注释t1.wait和t2.wait UI块,直到线程完成.所需的行为是在try/catch块中捕获错误而不阻塞UI.我想念什么?
My question is when I comment t1.wait and t2.wait Tasks are not blocking UI. However when I uncomment t1.wait and t2.wait UI blocks until thread is completed. The desired behavior is to catch errors in try/catch block without blocking UI. What Am I missing?
推荐答案
如果此操作在UI事件处理程序中运行,则可以将async
修饰符添加到方法签名中,并将t1.Wait()
更改为await t1
.这将把控制权返回给UI线程,并且在Thread.Sleep完成后,将继续执行并捕获任何异常.
If this is running within a UI event handler, you can add the async
modifer to the method signature and change t1.Wait()
to await t1
. This will return control to the UI thread, and when the Thread.Sleep has completed, the continuation will execute and any exceptions will be caught.
这篇关于异步等待块主界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!