-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExtensions.cs
44 lines (39 loc) · 1.56 KB
/
Extensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System;
using System.Threading.Tasks;
namespace Dapper
{
internal static class Extensions
{
/// <summary>
/// Creates a <see cref="Task{TResult}"/> with a less specific generic parameter that perfectly mirrors the
/// state of the specified <paramref name="task"/>.
/// </summary>
internal static Task<TTo> CastResult<TFrom, TTo>(this Task<TFrom> task)
where TFrom : TTo
{
if (task is null) throw new ArgumentNullException(nameof(task));
if (task.Status == TaskStatus.RanToCompletion)
return Task.FromResult((TTo)task.Result);
var source = new TaskCompletionSource<TTo>();
task.ContinueWith(OnTaskCompleted<TFrom, TTo>, state: source, TaskContinuationOptions.ExecuteSynchronously);
return source.Task;
}
private static void OnTaskCompleted<TFrom, TTo>(Task<TFrom> completedTask, object state)
where TFrom : TTo
{
var source = (TaskCompletionSource<TTo>)state;
switch (completedTask.Status)
{
case TaskStatus.RanToCompletion:
source.SetResult(completedTask.Result);
break;
case TaskStatus.Canceled:
source.SetCanceled();
break;
case TaskStatus.Faulted:
source.SetException(completedTask.Exception.InnerExceptions);
break;
}
}
}
}