我知道这个问题已经被问过好几次了,但是,我正在稍微考虑一下不同的变体。
public async Task<string> SomeAsyncMethod(string url)
{
// do some URL validation
if (!valid)
{
throw new Exception("some error");
}
// do async stuff now
return await GetFromUrl(url)
}
// now in caller
public async Task<string> SomeOtherAsyncMethod(string input)
{
var task = SomeAsyncMethod(input);
// there is potential chance that a validation fails and
//exception is thrown even before entering async parts of the called function
// do some independent stuff here
try
{
await task;
}
catch(Exception e)
{
// log error
}
// is the following code correct way to handle exceptions?
if (!task.IsFaulted)
{
return task.Result;
}
// log error from task.Exception
return null;
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,即使在控件进入方法的异步部分之前,也可能会发生验证失败并引发异常的情况。我们是否需要将第一个调用也包装在 try..catch 块周围?我的实验表明这没有用。相反,任务状态设置为“故障”。因此,我认为检查任务状态并相应地返回数据是正确的。C#专业人士可以评论一下吗?
正如您已经说过的,当您有一个async抛出异常的方法时,调用该方法将永远不会抛出异常,相反,返回的任务只会出错。即使在第一个异常之前抛出异常也是如此await。如果这是您想要的功能,那么您已经拥有它,无需更改任何内容。
| 归档时间: |
|
| 查看次数: |
4821 次 |
| 最近记录: |