Is there a way to Wait for a TPL Task without in throwing an exception?

走远了吗. 提交于 2019-12-05 03:03:58

You can use Task.WaitAny like:

        var task = Task.Run(() =>
        {
            // ...
            throw new Exception("Blah");
        });
        Task.WaitAny(task);
        if (task.IsFaulted)
        {
            var error = task.Exception;
            // ...
        }
        else if (task.IsCanceled)
        {
            // ...
        }
        else
        {
            // Success
        }

Unfortunately, this functionality is not built-in. Use this workaround:

 myTask.ContinueWith(_ => { }, TaskCOntonuationOptions.ExecuteSynchronously).Wait();

You can make this into an extension method.

You can't wait on a faulted task without raising an exception. But you can wait on a continuation to that task, which will complete only after the original task completed without raising an exception:

public static Task SwallowExceptions(this Task task)
{
    return task.ContinueWith(_ => { });
}

faultedTask.SwallowExceptions().Wait();
if (faultedTask.IsFaulted)
{
    // handle exception
}

If your task returns a value, you can represent that in the extensions method and return the actual value if there were no exceptions or the default value if there were:

public static Task<T> SwallowExceptions<T>(this Task<T> task)
{
    return task.ContinueWith(completedTask => 
        completedTask.IsFaulted 
            ? default(T) 
            : completedTask.Result);
}

Based on what you have written, might catching the exception and checking the IsFaulted property be your solution? IsFaulted

Catch the exception within the Task and return it in the result?

var task1 = Task.Factory.StartNew(() =>
{
    try
    {
        throw new MyCustomException("I'm bad, but not too bad!");
    }
    catch(Exception ex)
    {
        return new Result { Error = ex };
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!