How to make an exception in the async method (Task.FromException)

I just discovered that with .NET 4.6 a new method has appeared FromExceptionin an object Task, and I was wondering what is the best way to throw exceptions in a methodasync

Here are two examples:

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);
    }
}
+4
source share
1 answer

There is a difference in behavior between GetTest1()and GetTest2.

GetTest1()will not throw an exception when calling a method. Instead, it returns Task<string>. An exception will not be selected until this task is expected (we could also choose to check the task to see if it was possible to do this without even throwing an exception).

GetTest2() Task<string>

, , . GetTest(), , , , , Task.FromException, . , - , , , .

+3

Source: https://habr.com/ru/post/1667232/


All Articles