[英]Running parallel async tasks and return result in .NET Core Web API
[英]Find Result of Parallel Async Tasks
基於這個問題,我正在嘗試設置代碼以將多個圖像並行保存到Azure Blob存儲。 下面這個方法工作正常,等待Task.WhenAll(任務)等待所有人完成后再繼續。
唯一的麻煩是,我希望能夠找出每個在我們的數據庫中存儲信息的請求是否真的成功了。 _db.AddImageAsync返回一個bool,下面的代碼等待所有任務完成,但是當我檢查所有任務的結果時,每個都是假的(即使我在括號內實際返回true)。
Enumerable中的每個任務都表示,即使我逐步執行斷點並且每個任務都已執行,結果仍未計算。
var tasks = wantedSizes.Select(async (wantedSize, index) =>
{
var resize = size.CalculateResize(wantedSize.GetMaxSize());
var quality = wantedSize.GetQuality();
using (var output = ImageProcessHelper.Process(streams[index], resize, quality))
{
var path = await AzureBlobHelper.SaveFileAsync(output, FileType.Image);
var result = await _db.AddImageAsync(id, wantedSize, imageNumber, path);
return result;
}
});
await Task.WhenAll(tasks)
if (!tasks.All(task => task.Result))
return new ApiResponse(ResponseStatus.Fail);
任何幫助深表感謝!
因為.Select(
延遲求值並返回一個IEnumerable<Task<bool>>
你導致.Select(
當你多次遍歷結果時多次運行。在它上面拋出一個.ToList()
使它成為一個List<Task<bool>>
並且只執行.Select(
一次,多次枚舉將在返回的List<Task<bool>>
,這將沒有副作用。
var tasks = wantedSizes.Select(async (wantedSize, index) =>
{
var resize = size.CalculateResize(wantedSize.GetMaxSize());
var quality = wantedSize.GetQuality();
using (var output = ImageProcessHelper.Process(streams[index], resize, quality))
{
var path = await AzureBlobHelper.SaveFileAsync(output, FileType.Image);
//Double check your documentation, is _db.AddImageAsync thread safe?
var result = await _db.AddImageAsync(id, wantedSize, imageNumber, path);
return result;
}
}).ToList(); //We run the Select once here to process the .ToList().
await Task.WhenAll(tasks) //This is the first enumeration of the variable "tasks".
if (!tasks.All(task => task.Result)) //This is a 2nd enumeration of the variable.
return new ApiResponse(ResponseStatus.Fail);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.