/
AsyncInvocationRegion.cs
144 lines (122 loc) · 5.73 KB
/
AsyncInvocationRegion.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
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
// ***********************************************************************
// Copyright (c) 2013 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
#if NET_4_0 || NET_4_5
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
#if NET_4_5
using System.Runtime.ExceptionServices;
#endif
namespace NUnit.Framework.Internal
{
internal abstract class AsyncInvocationRegion : IDisposable
{
private const string TaskTypeName = "System.Threading.Tasks.Task";
private const string AsyncAttributeTypeName = "System.Runtime.CompilerServices.AsyncStateMachineAttribute";
#if NET_4_0
private static readonly Action<Exception> PreserveStackTrace;
static AsyncInvocationRegion()
{
var method = typeof(Exception).GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic);
if (method != null)
{
PreserveStackTrace = (Action<Exception>)Delegate.CreateDelegate(typeof (Action<Exception>), method);
}
else
{
PreserveStackTrace = _ => { };
}
}
#endif
private AsyncInvocationRegion()
{
}
public static AsyncInvocationRegion Create(Delegate @delegate)
{
return Create(@delegate.Method);
}
public static AsyncInvocationRegion Create(MethodInfo method)
{
if (!IsAsyncOperation(method))
throw new ArgumentException(@"Either asynchronous support is not available or an attempt
at wrapping a non-async method invocation in an async region was done");
if (method.ReturnType == typeof(void))
throw new ArgumentException("'async void' methods are not supported, please use 'async Task' instead");
return new AsyncTaskInvocationRegion();
}
public static bool IsAsyncOperation(MethodInfo method)
{
return method.ReturnType.FullName.StartsWith(TaskTypeName) ||
method.GetCustomAttributes(false).Any(attr => AsyncAttributeTypeName == attr.GetType().FullName);
}
public static bool IsAsyncOperation(Delegate @delegate)
{
return IsAsyncOperation(@delegate.Method);
}
/// <summary>
/// Waits for pending asynchronous operations to complete, if appropriate,
/// and returns a proper result of the invocation by unwrapping task results
/// </summary>
/// <param name="invocationResult">The raw result of the method invocation</param>
/// <returns>The unwrapped result, if necessary</returns>
public abstract object WaitForPendingOperationsToComplete(object invocationResult);
public virtual void Dispose()
{ }
private class AsyncTaskInvocationRegion : AsyncInvocationRegion
{
private const string TaskWaitMethod = "Wait";
private const string TaskResultProperty = "Result";
private const string SystemAggregateException = "System.AggregateException";
private const string InnerExceptionsProperty = "InnerExceptions";
private const BindingFlags TaskResultPropertyBindingFlags = BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public;
public override object WaitForPendingOperationsToComplete(object invocationResult)
{
try
{
invocationResult.GetType().GetMethod(TaskWaitMethod, new Type[0]).Invoke(invocationResult, null);
}
catch (TargetInvocationException e)
{
IList<Exception> innerExceptions = GetAllExceptions(e.InnerException);
#if NET_4_5
ExceptionDispatchInfo.Capture(innerExceptions[0]).Throw();
#elif NET_4_0
PreserveStackTrace(innerExceptions[0]);
throw innerExceptions[0];
#endif
}
PropertyInfo taskResultProperty = invocationResult.GetType().GetProperty(TaskResultProperty, TaskResultPropertyBindingFlags);
return taskResultProperty != null ? taskResultProperty.GetValue(invocationResult, null) : invocationResult;
}
private static IList<Exception> GetAllExceptions(Exception exception)
{
if (SystemAggregateException.Equals(exception.GetType().FullName))
return (IList<Exception>)exception.GetType().GetProperty(InnerExceptionsProperty).GetValue(exception, null);
return new Exception[] { exception };
}
}
}
}
#endif