我可以使用 async / await 来模拟后台工作者吗?

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

我试图避免将一堆 BackgroundWorker 链接在一起。我正在做的事情要求我在继续执行之前等待 UI 更新。显然,我不能使用 Sleep,因为这会阻止 UI 线程更新并破坏目的。我在下面找到了我认为是答案的代码,但 task.Wait(); 行似乎仍在阻塞 UI 线程。

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
}

我也尝试了以下,它做了同样的事情:

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
}

是否可以做我想做的事,如果可以,我做错了什么?

您需要 await 任务而不是阻止它。您可以在 async 方法中执行此操作。

现在,Main 不能是 async,但事件处理程序可以是(我猜这是你实际使用该代码的地方):

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

请注意,async void 只能用于事件处理程序。所有其他 async 方法都应该 return 一个任务。

使用Task.Run 意味着您使用的是ThreadPool 线程。要真正异步等待 UI 到 "do something",您应该使用 TaskCompletionSource。您创建它并且 await 它是 Task 属性 并在 UI 更改时完成该任务:

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);
}