在C#中,是否可以知道方法是否正在异步流程中执行?

问题描述 投票:0回答:1

我们可以有一个方法

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();
}
c# asynchronous async-await
1个回答
0
投票

异步方法的执行与常规方法没有太大区别。如果你的要求不是那么严格,你可以检查堆栈,看看该方法是否在内部运行

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.