Async wait block Main UI

后端 未结 3 791
长情又很酷
长情又很酷 2021-01-14 03:54

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 ContinueW

3条回答
  •  没有蜡笔的小新
    2021-01-14 04:19

    If you're going to use the Task-based Asynchronous Pattern, then you should use the recommended guidelines. I have an MSDN article describing many of them.

    In particular:

    • Use Task.Run instead of the Task constructor with Task.Start.
    • Use await instead of ContinueWith.
    • Do not use AttachedToParent.

    If you apply these changes, your code will then look like this:

    try
    {
      await Task.Run(() =>
      {
        Thread.Sleep(10000);
    
        // make the Task throw an exception
        MessageBox.Show("This is T1");
      });
      await Task.Run(() =>
      {
        Thread.Sleep(1000);
        MessageBox.Show("This is Continuation");
      });
    }
    catch (Exception ex)
    {
      MessageBox.Show(ex.Message);
    }  
    

提交回复
热议问题