C#Task.Wait()聚合异常

时间:2016-12-31 10:14:57

标签: c# task

我的代码:

void Method(){
Task T = Task.Factory.StartNew(() =>
{
    for (int i=0;i<count;i++)
    {
        textBox1.Text += "x";
        Thread.Sleep(500);
    }
});
T.Wait();
}

我想要这个任务等到一切都结束然后存在方法并且主线程恢复其工作... 但我在AggregateException was unhandled

上收到T.Wait();错误

这有什么问题?

3 个答案:

答案 0 :(得分:3)

更新UI控件时,您必须检查当前执行是否在UI线程上发生。如果情况并非如此,请按以下步骤操作:

void Method(){
Task T = Task.Factory.StartNew(() =>
{
    for (int i=0;i<count;i++)
    {
        UpdateUi functionToUpdateUi = UpdateTextBoxControl;
        if (textBox1.InvokeRequired)
            textBox1.BeginInvoke(functionToUpdateUi);

        //textBox1.Text += "x"; this is non-GUI thread. You can't update GUI controls like this
        Thread.Sleep(500);
    }
});
T.Wait();
}

//declaration of delegate signature
delegate void UpdateUi();    

//this is a new method which you will create separately
private void UpdateTextBoxControl()
{
    //this method gets executed on GUI thread so it safe
    textBox1.Text = "Changed the text from background thread.";
}

答案 1 :(得分:1)

您可以抓住AggregateException,看看所有正在运行的任务出了什么问题。

catch (AggregateException err)
{
    foreach (var e in err.InnerExceptions)
    {
        exception = err.InnerException;
    }
}

答案 2 :(得分:1)

我建议你不要自己开始搞乱开始任务。你可以这样重写它

int count = 10;
async Task MethodAsyncs()
{
    for (int i = 0; i < count; i++)
    {
        textBox1.Text += "x";
        await Task.Delay(500);
    }
}