Skip to content

Commit 841ff5b

Browse files
committed
Added observe exceptions extensions for tasks
1 parent d02ad24 commit 841ff5b

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// MADE Apps licenses this file to you under the MIT license.
2+
// See the LICENSE file in the project root for more information.
3+
4+
namespace MADE.Threading
5+
{
6+
using System;
7+
using System.Threading.Tasks;
8+
9+
/// <summary>
10+
/// Defines a collection of extensions for tasks.
11+
/// </summary>
12+
public static class TaskExtensions
13+
{
14+
/// <summary>
15+
/// Observes the exceptions of faulted tasks.
16+
/// </summary>
17+
/// <param name="task">The task to observe for exceptions.</param>
18+
/// <param name="onException">An action invoked when an exception is caught.</param>
19+
/// <returns>An asynchronous operation.</returns>
20+
public static Task AndObserveExceptions(this Task task, Action<Exception> onException = null)
21+
{
22+
task?.ContinueWith(
23+
t =>
24+
{
25+
AggregateException aggregateException = t.Exception?.Flatten();
26+
onException?.Invoke(aggregateException);
27+
},
28+
TaskContinuationOptions.OnlyOnFaulted);
29+
30+
return task;
31+
}
32+
33+
/// <summary>
34+
/// Observes the exceptions of faulted tasks.
35+
/// </summary>
36+
/// <param name="task">The task to observe for exceptions.</param>
37+
/// <param name="onException">An action invoked when an exception is caught.</param>
38+
/// <returns>An asynchronous operation.</returns>
39+
public static Task<T> AndObserveExceptions<T>(this Task<T> task, Action<Exception> onException = null)
40+
{
41+
task?.ContinueWith(
42+
t =>
43+
{
44+
AggregateException aggregateException = t.Exception?.Flatten();
45+
onException?.Invoke(aggregateException);
46+
},
47+
TaskContinuationOptions.OnlyOnFaulted);
48+
49+
return task;
50+
}
51+
}
52+
}

0 commit comments

Comments
 (0)