forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTaskExt.cs
More file actions
63 lines (55 loc) · 1.7 KB
/
TaskExt.cs
File metadata and controls
63 lines (55 loc) · 1.7 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
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ServiceStack
{
public static class TaskExt
{
public static Task<object> AsTaskException(this Exception ex)
{
var tcs = new TaskCompletionSource<object>();
tcs.SetException(ex);
return tcs.Task;
}
public static Task<T> AsTaskException<T>(this Exception ex)
{
var tcs = new TaskCompletionSource<T>();
tcs.SetException(ex);
return tcs.Task;
}
public static Task<T> AsTaskResult<T>(this T result)
{
var tcs = new TaskCompletionSource<T>();
tcs.SetResult(result);
return tcs.Task;
}
public static object GetResult(this Task task)
{
try
{
if (!task.IsCompleted)
task.Wait();
if (task is Task<object> taskObj)
return taskObj.Result;
var taskType = task.GetType();
if (!taskType.IsGenericType || taskType.FullName.Contains("VoidTaskResult"))
return null;
var props = TypeProperties.Get(taskType);
var fn = props.GetPublicGetter("Result");
return fn?.Invoke(task);
}
catch (TypeAccessException)
{
return null; //return null for void Task's
}
catch (Exception ex)
{
throw ex.UnwrapIfSingleException();
}
}
public static T GetResult<T>(this Task<T> task)
{
return (T)((Task)task).GetResult();
}
}
}