5

I have created a test application in Winform to learn exception handling in Task (c#). Target framework is 4.0. Following is my code for exception handling

        var task = Task.Factory.StartNew<DataTable>(() => getDataTable(Convert.ToInt32  (this.textBoxOptionVal.Text)));

        task.ContinueWith(t =>
        {
            this.dataGridViewData.DataSource = t.Result as DataTable;
            this.textBoxRetVal.Text = "Success" ;
        },
        CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());

        task.ContinueWith(t =>
        {
            // Update UI (and UI-related data) here: failed status.
            // t.Exception contains the occured exception.
            AggregateException aggregateException = t.Exception;
            aggregateException.Handle(exception => true);
            this.dataGridViewData.DataSource = null;
            this.textBoxRetVal.Text = "Exception Thrown";
        },
        CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());

This works fine. If any exception is thrown from getDataTable method then the continuewith OnlyOnFaulted block of code is executed. But then I commented out all the statements in ContinueWith OnlyOnfaulted block and also added a config file with following content

<?xml version="1.0"?>
 <configuration>
  <runtime>
    <ThrowUnobservedTaskExceptions enabled="true"/>
  </runtime>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
 </configuration>

But the issue is even now when I run the code and an exception is thrown from getDataTable method, the exception is swallon and the process is not getting terminated. What could be the cause? Please help.

2 Answers 2

4

Tasks are only checked for unobserved exceptions when they are finalized by the garbage collector:

In the .NET Framework 4, by default, if a Task that has an unobserved exception is garbage collected, the finalizer throws an exception and terminates the process. The termination of the process is determined by the timing of garbage collection and finalization.

https://msdn.microsoft.com/en-us/library/jj160346

Here is the a sample program which triggers this behaviour:

Program.cs

using System;
using System.Threading;
using System.Threading.Tasks;

namespace UnobservedTaskException
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Runtime Version: {0}", Environment.Version);

            var task = Task.Factory.StartNew<int>(() =>
            {
                throw new Exception("Calculation in task failed");
            });

            while (!task.IsFaulted)
            {
                Thread.Sleep(1);
            }

            task = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }
}

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <runtime>
    <ThrowUnobservedTaskExceptions enabled="true"/>
  </runtime>
</configuration>

Output

Runtime Version: 4.0.30319.42000

Unhandled Exception: System.AggregateException: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. ---> System.Exception: Calculation in task failed
   at UnobservedTaskException.Program.<Main>b__0() in Program.cs:line 15
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.TaskExceptionHolder.Finalize()

Note that even though the documentation states that the default behaviour under .NET Framework 4 is to terminate the process on an unobserved Task exception I still had to set <ThrowUnobservedTaskExceptions enabled="true"/> to get the process to die.

1

While I cannot answer the original question, I am hoping to provide some alternatives to solve the root issue. Its worth noting I've tried using ThrowUnobservedTaskExceptions flag and doesn't seem to make a difference for me either. Maybe it is because we are building in .net 4.0 and it doesn't recognize the flag. I also I tried these alternatives. and still didn't have any luck. If someone else could answer why it doesn't seem to work, that would still be appreciated.

  • By setting the environment variable COMPlus_ThrowUnobservedTaskExceptions (set COMPlus_ThrowUnobservedTaskExceptions=1).

  • By setting the registry DWORD value ThrowUnobservedTaskExceptions = 1 in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft.NETFramework key.

That being said here are some alternatives that may help you get by.

If you are using .NET 4.5 or .Net 4.0 with Microsoft.BCL.Async nuget package you could use the await keyword before your calls which would cause the exceptions to be observed

await task.ContinueWith(t =>

If you are stuck with.Net 4.0 and can't install the Microsoft.BCL.Async package...then you could just try calling Task.Wait()

   task.ContinueWith(t =>
    {
        this.dataGridViewData.DataSource = t.Result as DataTable;
        this.textBoxRetVal.Text = "Success" ;
    },
    CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());
    task.Wait();

By using Wait or Await, the code will actually care about the results of the asynchronous function it was calling and it will observe the exceptions that occur. Without doing that it will ignore those exceptions as noted in this MSDN document. From there you will be able to simply handle the unexpected exception like you would any other in your application

If that's not an option, you could also use the TaskScheduler.UnobservedTaskException event to listen for unobserved exceptions

[STAThread]
    public static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.ThreadException += ThreadExceptionHandler;
        AppDomain.CurrentDomain.UnhandledException += new System.UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

        Application.Run(new Form1());
    }

    static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
    {
        //log or display the exception
    }

    static void CurrentDomain_UnhandledException(object sender, System.UnhandledExceptionEventArgs e)
    {
        //log or display the exception
    }

   private static void ThreadExceptionHandler(object sender, System.Threading.ThreadExceptionEventArgs args)
    {
        //log or display the exception
    }

A good resource regarding dealing with unobserved exceptions http://blogs.msdn.com/b/pfxteam/archive/2011/09/28/10217876.aspx

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.