我们可以有一个方法
IsInAsyncContext
来识别控件是否位于异步执行流中吗?检查以下用法。
public static void Main()
{
IsInAsyncContext(); // Should return false.
AsyncMethod().GetAwaiter().GetResult();
SyncMethod();
}
private static async Task AsyncMethod()
{
IsInAsyncContext(); // Should return true.
SyncMethod();
}
private static void SyncMethod()
{
// Should return false if called from Main, true if called from AsyncMethod.
IsInAsyncContext();
}
异步方法的执行与常规方法没有太大区别。如果你的要求不是那么严格,你可以检查堆栈,看看该方法是否在内部运行
IAsyncStateMachine.MoveNext
。
public static bool IsInAsyncContext()
{
var st = new StackTrace(true);
for(int i = 0; i < st.FrameCount; ++i)
if(st.GetFrame(i)?.GetMethod()?.DeclaringType?.
GetInterface("System.Runtime.CompilerServices.IAsyncStateMachine") != null)
return true;
return false;
}