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

Sta*_*ity 2 .net c# multithreading task-parallel-library async-await

我试图避免将一堆BackgroundWorkers连在一起.我正在做一些事情,要求我在继续执行之前等待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
}
Run Code Online (Sandbox Code Playgroud)

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

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
}
Run Code Online (Sandbox Code Playgroud)

是否有可能做我想做的事情,如果是这样,我做错了什么?

i3a*_*non 6

您需要await执行任务而不是阻止它.你可以在一个async方法中做到这一点.

现在,Main不能async只是一个事件处理程序(我猜你在哪里实际使用该代码):

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

请注意,它async void应仅用于事件处理程序.所有其他async方法都应该返回一个任务.

使用Task.Run意味着您使用ThreadPool线程.要真正等待UI以"做某事"你应该使用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);
}
Run Code Online (Sandbox Code Playgroud)