Search code examples
c#.netwindows-phone-8

How can I catch an exception that occurs in Tasks when using Task.WhenAll()?


I tried putting the try catch around the Task.WhenAll(tasks) but it did not catch anything. In one of my tasks I tried to artificially generate an exception by using Substring on an empty string. But all that happens is the app crashes and defaults to Application_UnhandledException.

    private async void RunTasks()
    {

        tasks[0] = HttpExtensions.GetMyData("http://www....");

        tasks[1] = HttpExtensions.GetMyData("http://www.....");

        tasks[2] = GeoLocate.OneShotGeoLocate();

        try
        {
            await Task.WhenAll(tasks);
        }
        catch (AggregateException ae)
        {

            App.ViewModel.ErrorMessage = ae.Message;

        }

 }

Solution

  • This worked thanks to 'nakiya'

    private async void RunTasks()
    {
    
        tasks[0] = HttpExtensions.GetMyData("http://www....");
    
        tasks[1] = HttpExtensions.GetMyData("http://www.....");
    
        tasks[2] = GeoLocate.OneShotGeoLocate();
    
        try
        {
            await Task.WhenAll(tasks);
        }
        catch (Exception ae)
        {
    
            App.ViewModel.ErrorMessage = ae.Message;
    
        }
    
    }