I read several topics about TaskCancellations .. However, I can not find a solution for a simple question: how to get the default value when my task fails?
I canβt (!) Change the task itself and put a try catch chip around it. I could, of course, play with try-catch, but I would like to handle this with ContinueWith - if possible.
public Task<List<string>> LoadExample() { Task<List<string>> task = LoadMyExampleTask(); task.ContinueWith(t => default(List<string>), TaskContinuationOptions.OnlyOnFaulted); return task; }
I thought this would be the right way to deal with this problem. However, my application throws a JsonParseException (which is called in LoadMyExampleTask ). I would expect to get a null or (even better) empty list.
In fact, all I want is:
var emptyOrFilledList = await LoadExample(); // guaranteed no exception thrown
Based on Luaan's excellent answer, I wrote an extension method with the defaultValue parameter:
public static Task<T> DefaultIfFaulted<T>(this Task<T> @this, T defaultValue = default(T)) { return @this.ContinueWith(t => t.IsCompleted ? t.Result : defaultValue); }
Edit: await myTask.DefaultifFaulted() just threw it away
[ERROR] FATAL UNHANDLED EXCEPTION: System.AggregateException
Are you sure all exceptions are caught?
c # task-parallel-library task
Frame91
source share