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
73 lines (63 loc) · 2.38 KB
/
TaskExt.cs
File metadata and controls
73 lines (63 loc) · 2.38 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
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();
}
private static readonly TaskFactory SyncTaskFactory = new TaskFactory(CancellationToken.None,
TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default);
public static void RunSync(Func<Task> task) => SyncTaskFactory.StartNew(task).Unwrap().GetAwaiter().GetResult();
public static TResult RunSync<TResult>(Func<Task<TResult>> task) => SyncTaskFactory.StartNew(task).Unwrap().GetAwaiter().GetResult();
#if NET472 || NETSTANDARD2_0
public static ValueTask AsValueTask(this Task task) => new ValueTask(task);
public static ValueTask<T> AsValueTask<T>(this Task<T> task) => new ValueTask<T>(task);
#endif
}
}