Bid*_*dou 12 .net c# exception task async-await
我才发现,原来,因为.NET 4.6,有一个新的方法FromException
上Task
的对象,我想知道什么是在抛出异常的最佳方式async
方法
这里有两个例子:
internal class Program
{
public static void Main(string[] args)
{
MainAsync().Wait();
}
private static async Task MainAsync()
{
try
{
Program p = new Program();
string x = await p.GetTest1(@"C:\temp1");
}
catch (Exception e)
{
// Do something here
}
}
// Using the new FromException method
private Task<string> GetTest1(string filePath)
{
if (!Directory.Exists(filePath))
{
return Task.FromException<string>(new DirectoryNotFoundException("Invalid directory name."));
}
return Task.FromResult(filePath);
}
// Using the normal throw keyword
private Task<string> GetTest2(string filePath)
{
if (!Directory.Exists(filePath))
{
throw new DirectoryNotFoundException("Invalid directory name.");
}
return Task.FromResult(filePath);
}
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*t_R 15
GetTest1()
和之间的行为有所不同GetTest2
.
GetTest1()
调用方法时不会抛出异常.相反,它返回一个Task<string>
.在等待该任务之前不会抛出异常(我们也可以选择检查任务是否成功而不抛出异常).
相反GetTest2()
,在调用时立即抛出异常而不返回Task<string>
我想你使用哪一个取决于所需的行为.如果我有一堆GetTest()
任务,我想并行运行,我希望执行继续执行那些成功的任务,然后我将使用Task.FromException
它允许我检查每个任务的结果并采取相应的行动.相反,如果列表中的任何异常意味着我不希望继续执行,我可能会抛出异常.
归档时间: |
|
查看次数: |
10089 次 |
最近记录: |