如何在异步方法中抛出异常(Task.FromException)

时间:2017-01-19 07:41:15

标签: c# .net exception async-await task

我刚刚发现自.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);
    }
}

1 个答案:

答案 0 :(得分:8)

GetTest1()GetTest2之间的行为存在差异。

调用方法时,

GetTest1()不会抛出异常。而是返回Task<string>。在等待该任务之前不会抛出异常(我们也可以选择检查任务是否成功而不抛出异常)。

相反,GetTest2()在调用时立即抛出异常而不返回Task<string>

我猜你使用哪一个取决于所需的行为。如果我有一堆GetTest()任务,我想并行运行,我希望执行继续执行那些成功的任务,然后我会使用Task.FromException,这样我就可以检查每个任务的结果并采取行动因此。相反,如果列表中的任何异常意味着我不希望继续执行,我可能会抛出异常。