j0w*_*j0w 4 .net c# asynchronous core async-await
我试图进入异步的事情。我想让我的方法之一异步,因为它需要一段时间才能完成,所以我尝试了这个:
public static async Task GenerateExcelFile(HashSet<string> codes, ContestViewModel model)
{
var totalCodeToDistribute = model.NbrTotalCodes - (model.NbrCodesToPrinter + model.NbrCodesToClientService);
if (model.NbrTotalCodes > 0)
{
using (var package = new ExcelPackage())
{
await DoStuff(some, variables, here);
package.SaveAs(fileInfo);
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以我可以像这样在我的控制器中调用它:
await FilesGenerationUtils.GenerateExcelFile(uniqueCodesHashSet, model);
Run Code Online (Sandbox Code Playgroud)
但是当涉及到“await”关键字时,它说“Type void is not awaitable”
这是等待 void 方法的一种方式还是不是最佳实践?如果是这样,最好的方法是什么?
编辑:控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(ContestViewModel model)
{
var contentRootPath = _hostingEnvironment.ContentRootPath;
DirectoryUtils.OutputDir = new DirectoryInfo(contentRootPath + Path.DirectorySeparatorChar
+ "_CodesUniques" + Path.DirectorySeparatorChar
+ model.ProjectName +
Path.DirectorySeparatorChar
+ "_Codes");
var directory = DirectoryUtils.OutputDir;
var selectedAnswer = model.SelectedAnswer;
var uniqueCodesHashSet = new HashSet<string>();
try
{
while (uniqueCodesHashSet.Count < model.NbrTotalCodes)
{
var generatedString = RandomStringsUtils.Generate(model.AllowedChars, model.UniqueCodeLength);
uniqueCodesHashSet.Add(generatedString.ToUpper());
}
#region FOR TXT FILES
if (selectedAnswer == FileExtension.TXT.GetStringValue())
{
await FilesGenerationUtils.GenerateTxtFiles(uniqueCodesHashSet, model, directory);
}
#endregion
#region FOR XLSX FILES
if (selectedAnswer == FileExtension.XLSX.GetStringValue())
{
await FilesGenerationUtils.GenerateExcelFile(uniqueCodesHashSet, model);
}
#endregion
return View();
}
catch (Exception ex)
{
Console.Write(ex);
}
return View();
}
Run Code Online (Sandbox Code Playgroud)
如果我明白你们在说什么,我必须创建一个可以等待的方法。如果我使用这样的方法,我会正确吗:
public static Task DoStuff(ExcelWorksheet sheet, HashSet<string> codes, int rowIndex, int count, int maxRowValue)
{
foreach (var code in codes)
{
sheet.Row(rowIndex);
sheet.Cells[rowIndex, 1].Value = code;
rowIndex++;
count++;
if (rowIndex == maxRowValue && count < (codes.Count - 1))
{
sheet.InsertColumn(1, 1);
rowIndex = 1;
}
}
//What should be returned?!
return null;
}
Run Code Online (Sandbox Code Playgroud)
您可以编写异步 void 方法,但不能等待这些方法:
public static class Program
{
public static async Task Main()
{
const int mainDelayInMs = 500;
AsyncVoidMethod();
await Task.Delay(mainDelayInMs);
Console.WriteLine($"end of {nameof(Main)}");
}
static async void AsyncVoidMethod()
{
await Task.Delay(1000);
Console.WriteLine($"end of {nameof(AsyncVoidMethod)}");
}
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的 AsyncVoidMethod 是异步的,但我不能写await AsyncVoidMethod();.
不应(大多数情况下)不使用异步 void 方法,因为您无法等待任务完成,并且可能无法处理抛出的任何异常(因此它可能会使您的应用程序崩溃):为什么 void async 是坏的?
| 归档时间: |
|
| 查看次数: |
6677 次 |
| 最近记录: |