簡體   English   中英

我可以使用async / await模擬后台工作者嗎?

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

我試圖避免將一堆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
}

我還嘗試了以下操作,它們的作用相同:

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方法應返回任務。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM