之前,我有這樣的異步代碼等待返回任務完成
private async Task<InvalidInvoiceViewModel> ValidateInsertedDataInRawTables(string uploadPath, long batchId)
{
var direcotryPath = Path.Combine(uploadPath, batchId.ToString());
var allFiles = Directory.GetFiles(direcotryPath);
var invoiceRawList = new List<InvoiceRaw>();
var invoiceDetailRawList = new List<InvoiceDetailRaw>();
await Task.Run(() => allFiles.ToList().ForEach(async file =>
{
var fileName = Path.GetFileNameWithoutExtension(file);
switch (fileName)
{
case "invoice":
invoiceRawList = await ValidateInsertedDataInRawTablesForInvoiceAsync(batchId);
break;
case "invoicedetails":
invoiceDetailRawList = await ValidateInsertedDataInRawTablesForInvoiceDetailAsync(batchId);
break;
}
}));
var invalidInvoiceViewModel = new InvalidInvoiceViewModel
{
InvoiceRawList = invoiceRawList ,
InvoiceDetailRawList = invoiceDetailRawList
};
return invalidInvoiceViewModel;
}
但發生的事情是,在我總是得到0計數在InvoiceRawList
和InvoiceDetailRawList
兩者。我發現該方法返回之前異步lambda完成其處理。 (在Chrome控制檯中,結果出現在網絡選項卡中,但在此之後會觸發ValidateInsertedDataInRawTablesForInvoiceAsync
中的調試點)。我正在等待爲此lambda創建的Task.Run
。我在這裏做錯了什麼?評論
如果我這樣做,以後
更新,它不會編譯,我把它改成...
private async Task<InvalidInvoiceViewModel> ValidateInsertedDataInRawTables(string uploadPath, long batchId)
{
var direcotryPath = Path.Combine(uploadPath, batchId.ToString());
var allFiles = Directory.GetFiles(direcotryPath);
var invoiceRawList = new List<InvoiceRaw>();
var invoiceDetailRawList = new List<InvoiceDetailRaw>();
await Task.Run(async() => await allFiles.ToList().ForEach(async file =>
{
var fileName = Path.GetFileNameWithoutExtension(file);
switch (fileName)
{
case "invoice":
invoiceRawList = await ValidateInsertedDataInRawTablesForInvoiceAsync(batchId);
break;
case "invoicedetails":
invoiceDetailRawList = await ValidateInsertedDataInRawTablesForInvoiceDetailAsync(batchId);
break;
}
}));
var invalidInvoiceViewModel = new InvalidInvoiceViewModel
{
InvoiceRawList = invoiceRawList ,
InvoiceDetailRawList = invoiceDetailRawList
};
return invalidInvoiceViewModel;
}
,並說不能等待無效。我知道這意味着什麼,但是我該如何解決這個問題? List.ForEach是一個無效的方法。
您並未等待您的ForEach循環體,它也是異步的。 – Evk
並**每個**文件設置invoiceRawList和invoiceDetailRawList –
@Evk:我做到了,但現在它甚至不會編譯! – Razort4x