Alternative for Task.Wait in UI thread

心不动则不痛 提交于 2021-02-07 12:58:26

问题


I know it is bad to call Task.Wait in UI thread. It causes a deadlock. Please refer to

Constructor invoke async method

Await, and UI, and deadlocks! Oh my!

Take the following code:

    public MainPage()
    {
        this.InitializeComponent();

        step0();
        step1();
    }

    private async Task step0()
    {
        await Task.Delay(5000);
        System.Diagnostics.Debug.WriteLine("step 0");
    }

    private async Task step1()
    {
        await Task.Delay(3000);
        System.Diagnostics.Debug.WriteLine("step 1");
    }
}

How can I ensure that "step 0" is always being printed before "step 1"? Using Task.Wait would cause deadlock. This is Windows Store App


回答1:


You can use Task.ContinueWith to chain the tasks together so that they happen sequentially.

public MainPage()
{
    this.InitializeComponent();

    step0().ContinueWith(t => step1());
}

Also, Alexei's comment is correct. Task.Wait will block the UI thread. Deadlocks are something else.




回答2:


You can't have an async constructor, period.

So whatever you do, you'll need to handle the situation where your constructor returns without having completed its async initialization.

There are a few ways of handling this. If the "steps" are loading resources, then you can do something like this (using the AsyncLazy type from my blog, Stephen Toub's blog, or my AsyncEx library - they're all nearly the same):

private readonly AsyncLazy<MyResource> resource;

public MainPage()
{
  resource = new AsyncLazy<MyResource>(async () =>
  {
    var a = await step0();
    var b = await step1();
    return new MyResource(a, b); // or whatever
  });
  resource.Start(); // start step0
}

public async Task MethodThatNeedsResource()
{
  var r = await resource; // ensure step1 is complete before continuing
}

It's also possible to do this with an async void method or ContinueWith, but you'll have to carefully consider error handling with those approaches.

  • The AsyncLazy approach will capture errors and raise them whenever await resource is executed.
  • The async void approach will throw errors immediately to the SynchronizationContext.
  • The naive ContinueWith approach will silently ignore all errors.

Whichever approach you take, I recommend having some notification in the UI that the initialization is in progress. (And as a side note, I think all of this should go into a ViewModel or Model class rather than MainPage).



来源:https://stackoverflow.com/questions/13411339/alternative-for-task-wait-in-ui-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!