似乎在 Blazor 服务器应用程序中,我们鼓励尽可能使用 Async,我通常理解为什么。就是说-有人能不能解释一下使用异步函数时的一般期望并为我填写一些缺失的知识-我对那里的所有信息感到困惑,需要一些特定于我正在做的事情的信息,以帮我理解。
我试图在可能的情况下坚持使用 async 并且在大多数情况下这样做相当容易,但是在调用某些函数时,使它们异步似乎有点过分(或者是吗?)。在下面的示例中 - 从异步函数中调用非异步“ValidateEvent”函数。
所以我的问题是......我应该:
a)从异步函数中正常调用它(这似乎破坏了异步点)例如:“var validationResult = ValidateEvent(objDto);”?
b)使用 Task.Run 调用它,例如:“await Task.Run(() =>ValidateEvent(objDto));”?
c)将这个简单的 IF/ELSE 方法转换为 Async 函数?
提前感谢您的任何帮助/建议。
//example async function, that itself calls the other non-async function.
public async Task<Response> AddAsync(ObjDto objDto)
{
// a) Call it normally?
var validationResult = ValidateEvent(objDto);
// b) Calling it using Task.Run?
var validationResult = await Task.Run(() =>ValidateEvent(objDto));
//Do stuff asynchronously here
...
await _db.AddAsync(objDto);
await _db.SaveChangesAsync();
...
}
验证函数:
c) 我真的应该将其转换为异步,因为它只是一系列“IF 和 ELSE”(下面进一步进行异步转换)
//Non-Async version
public ResponseObj ValidateEvent(ObjDto obj)
{
ResponseObj responseObj = new();
string stringErrors = "";
//If not full day, check that end date is not before start date
if (!obj.IsFullDay)
{
if (obj.EndTime < obj.StartTime)
stringErrors += ("End date cannot be before the start date<br />");
}
...other code removed for brevity
if (string.IsNullOrEmpty(stringErrors)) //Success
{
responseObj.Status = responseObj.Success;
}
else //errors
{
responseObj.Status = responseObj.Error;
responseObj.Message = stringErrors;
}
return responseObj;
}
// 异步转换示例 - 是否值得使用 Task.Run 进行转换?
//Async conversion
public async Task<ResponseObj> ValidateEvent(ObjDto obj)
{
ResponseObj responseObj = new();
string stringErrors = "";
await Task.Run(() =>
{
//If not full day, check that end date is not before start date
if (!obj.IsFullDay)
{
if (obj.EndTime < obj.StartTime)
stringErrors += ("End date cannot be before the start date<br />");
}
if (string.IsNullOrEmpty(stringErrors)) //Success
{
responseObj.Status = responseObj.Success;
}
else //errors
{
responseObj.Status = responseObj.Error;
responseObj.Message = stringErrors;
}
}
);
return responseObj;
}
再次,提前感谢您在理解一般情况下的最佳方式方面的任何帮助/建议。
a) 从 Async 函数中正常调用它...
是的
...(这似乎打败了异步点)
不,它没有。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句