forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsyncExtensions.cs
More file actions
82 lines (75 loc) · 2.33 KB
/
Copy pathAsyncExtensions.cs
File metadata and controls
82 lines (75 loc) · 2.33 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ServiceStack
{
internal static class AsyncExtensions
{
//http://bradwilson.typepad.com/blog/2012/04/tpl-and-servers-pt3.html
public static Task<TOut> Continue<TOut>(
this Task task,
Func<Task, TOut> next)
{
if (task.IsCompleted)
{
var tcs = new TaskCompletionSource<TOut>();
try
{
var res = next(task);
tcs.TrySetResult(res);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
return tcs.Task;
}
return ContinueClosure(task, next);
}
static Task<TOut> ContinueClosure<TOut>(
Task task,
Func<Task, TOut> next)
{
var ctxt = SynchronizationContext.Current;
return HostContext.Async.ContinueWith(task, innerTask =>
{
var tcs = new TaskCompletionSource<TOut>();
try
{
if (ctxt != null)
{
ctxt.Post(state =>
{
try
{
var res = next(innerTask);
tcs.TrySetResult(res);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}, state: null);
}
else
{
var res = next(innerTask);
if (res is Task t && t.IsFaulted)
{
tcs.TrySetException(t.Exception);
}
else
{
tcs.TrySetResult(res);
}
}
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
return tcs.Task;
}).Unwrap();
}
}
}