簡體   English   中英

異步任務等待另一個任務

[英]Async task waiting for another task

我的代碼如下:

private async Task<bool> DoAsyncThing()
{
  await doOtherThings();
} 

private async Task<bool> DoAsyncThing2()
{
  await doOtherThings2();
} 

private async Task<bool> SaveAll()
{
   return await _context.SaveChangesAsync() > 0;
}

public async Task<bool> FirstBatchProcess()
{
    var tasks = new List<Task<bool>>();
    ...
    users.Foreach(user => {
        task.Add(this.DoAsyncThing());
    });
    await Task.WhenAll(tasks);
    return await this.SaveAll();
}

public async Task<bool> SecondBatchProcess()
{
    // get all data from batch 1 and then do calculation
    var tasks = new List<Task<bool>>();
    ...
    users.Foreach(user => {
        task.Add(this.DoAsyncThing2());
    });
    await Task.WhenAll(tasks);
    return await this.SaveAll();
}


public async Task<bool> ProcessAll()
{
    await this.FirstBatchProcess();
    await this.SecondBatchProcess();
}

在ProcessAll中,我想在執行SecondBatchProcess之前先完成firstBatchProcess。 因為我有來自FirstBatchPRocess的一些數據,以便稍后在SecondBatchProcess中使用。 如果我運行此代碼,兩者都將執行異步並導致錯誤,因為SecondBatchProcess需要從FirstBatchProcess生成的數據。

注意:兩個BatchProcesses包含多個異步循環所以我使用Task.WhenAll()如何等待FirstBatchProcess完成然后執行SecondBatchProcess?

更新

所以當我調用Task.Wait()時,它會等待這個任務完成然后它會繼續另一個進程嗎?

既然你編輯了你的問題,如果我理解正確(我正在讀行)

await this.FirstBatchProcess();  // will wait for this to finish
await this.SecondBatchProcess(); // will wait for this to finish

答案是肯定的,在FirstBatchProcess啟動的所有任務FirstBatchProcess將在它執行SecondBatchProcess之前完成

原版的

Task.WhenAll方法

創建將在所有提供的任務完成后完成的任務

我想你可能await運算符感到困惑

等待(C#參考)

await運算符應用於異步方法中的任務,以在方法執行中插入暫停點, 直到等待的任務完成 該任務代表了正在進行的工

它實際上等待!

你在這里完整的演示

private static async Task DoAsyncThing()
{
    Console.WriteLine("waiting");
    await Task.Delay(1000);
    Console.WriteLine("waited");
}

private static async Task SaveAll()
{
    Console.WriteLine("Saving");
    await Task.Delay(1000);
}

public static async Task ProcessAll()
{
    var tasks = new List<Task>();
    for (int i = 0; i < 10; i++)
    {
        tasks.Add(DoAsyncThing());
    }

    await Task.WhenAll(tasks);
    await SaveAll();
    Console.WriteLine("Saved");
}

public static void Main()
{
    ProcessAll().Wait();
    Console.WriteLine("sdf");
}

產量

waiting
waiting
waiting
waiting
waiting
waiting
waiting
waiting
waiting
waiting
waited
waited
waited
waited
waited
waited
waited
waited
waited
waited
Saving
Saved
sdf

所有任務都已完成。

如何使用Task.Factory.StartNew();

Task.Factory.StartNew(() =>
{
     return DoAsyncThing();
}).ContinueWith(x =>
{
     if (x.Result)
        SaveAll();
});

如果DoAsyncThing()對UI執行某些操作,則應將TaskScheduler.FromCurrentSynchronizationContext()StartNew()

我希望它有所幫助。

謝謝。

暫無
暫無

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

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