Recently I was asked about a specific scenario when some code was being converted into using TAP and this was code that already used tasks. Since the existing code used the "IsFaulted" property a lot I came up with this little extension method making it easy to see if a task failed or not using the await keyword but without adding a lot of exception handling.
1: public static Task<bool> WaitAsync(this Task task)
2: {
3: var tcs = new TaskCompletionSource<bool>();
4: task.ContinueWith(
5: t => tcs.TrySetResult(!(t.IsFaulted || t.IsCanceled)));
6: return tcs.Task;
7: }
or
public static Task<bool> WaitAsync(this Task task)
{
return task.ContinueWith(
t => !(t.IsFaulted || t.IsCanceled),
TaskContinuationOptions.ExecuteSynchronously);
}
Read more: Being Cellfish
QR:
0 comments:
Post a Comment