简体   繁体   中英

Task with built in exception handling?

When using Tasks you have to take special care in handling exceptions, here is an example :

class Program
{
    static void Main(string[] args)
    {
        Task<int> task = new Task<int>(Test);
        task.ContinueWith(ExceptionHandler, TaskContinuationOptions.OnlyOnFaulted);
        task.Start();
        Console.ReadLine();
    }

    static int Test()
    {
        throw new Exception();
    }

    static void ExceptionHandler(Task<int> task)
    {
        var exception = task.Exception;
        Console.WriteLine(exception);
    }
}

From here

My question is if there is any way to make a custom Task that will handle(log to service) all exceptions without manually stating it by the developer? Some kind of help heritage.

You could create MyLoggingTask as a subclass of Task, implementing the constructors that are relevant to you, or all of them to be on the safe side (I see 8 of them in .NET Framework 4.5), and override the Start() method.

Then either replace every Task usage with MyLoggingTask + a reference to the namespace of your subclass, or minimize the 'manual' aspect with using Task = Your.NameSpace.MyLoggingTask , creating a Task alias that is in fact your own class.

As an alternative, you could create an Extension Method public static StartWithLogging<T>(this Task<T> task) which takes care of the ContinueWith . Then replace every Start() call with StartWithLogging() + reference the namespace of your extension class.

I'm afraid there are no easier options, and some degree of 'manually stating' will always be needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM