gpt4 book ai didi

c# - 如何在 ASP.NET Core 中对 void 方法使用异步/等待?

转载 作者:行者123 更新时间:2023-11-30 14:05:41 25 4
gpt4 key购买 nike

我正试图进入异步的话题。我想让我的方法之一异步,因为它需要一段时间才能完成,所以我尝试了这个:

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

所以我可以在我的 Controller 中这样调用它:

 await FilesGenerationUtils.GenerateExcelFile(uniqueCodesHashSet, model);

但是当涉及到“await”关键字时,它说“Type void is not awaitable”

这是一种等待 void 方法的方法还是不是最佳实践?如果是这样,最好的方法是什么?

Controller :

[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();
}

如果我理解你们所说的,我必须创建一个可等待的方法。如果我选择这样的东西,我走对了吗:

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;
}

最佳答案

您可以编写 async 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)}");
}
}

如您所见,AsyncVoidMethod 是异步的,但我无法编写 await AsyncVoidMethod();

不应该(大多数时候)使用异步无效方法,因为您不能等待任务完成,并且抛出的任何异常都可能无法处理(因此它可能使您的应用程序崩溃):Why exactly is void async bad?

关于c# - 如何在 ASP.NET Core 中对 void 方法使用异步/等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54933176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com