简体   繁体   中英

Can I use async / await to simulate a background worker?

I'm trying to avoid having to chain a bunch of BackgroundWorkers together. I'm doing something that requires me to wait for the UI to update before continuing execution. Obviously, I can't use Sleep, as this blocks the UI thread from updating and defeats the purpose. I found the code below which I thought was the answer, but it appears the task.Wait(); line is still blocking the UI thread.

static void Main(string[] args)
{
    var task = Task.Run(() => DoSomething());
    task.Wait();
    // once the task completes, now do more
}

static void DoSomething()
{
    // something here that is looking for the UI to change
}

I also tried the following, which did the same thing:

static void Main(string[] args)
{
    var task = Task.Run(() => DoSomethingAsync());
    task.Wait();
    // once the task completes, now do more
}

private async Task DoSomethingAsync()
{
    // something here that is looking for the UI to change
}

Is it possible to do what I want, and if so, what am I doing wrong?

You need to await the task instead of blocking on it. You can do that inside an async method.

Now, Main can't be async but an event handler can be (which I guess is where you actually use that code):

public async void EventHandler(object sender, EventArgs e)
{
    await Task.Run(() => DoSomething()); // wait asynchronously
    // continue on the UI thread
}

Note that it's async void which should only be used on event handlers. All other async methods should return a task.

Using Task.Run means your using a ThreadPool thread. To really wait asynchronously for the UI to "do something" you should use TaskCompletionSource . You create it and await it's Task property and you complete that task when the UI changed:

public async void EventHandler(object sender, EventArgs e)
{
    _tcs = new TaskCompletionSource<bool>();
    await _tcs.Task;
}

public void UIChanged(object sender, EventArgs e)
{
    _tcs.SetResult(false);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM