在控制台应用程序中模拟异步死锁

woo*_*hoh 6 c# asynchronous async-await

通常,UI线程或ASP.NET上下文中会出现异步死锁.我正在尝试模拟控制台应用程序中的死锁,以便我可以对我的库代码进行单元测试.

所以这是我的尝试:

class Program
{
    private static async Task DelayAsync()
    {
        Console.WriteLine( "DelayAsync.Start" );
        await Task.Delay( 1000 );
        Console.WriteLine( "DelayAsync.End" );
    }

    // This method causes a deadlock when called in a GUI or ASP.NET context.
    public static void Deadlock()
    {
        Console.WriteLine( "Deadlock.Start" );
        // Start the delay.
        var delayTask = DelayAsync();
        // Wait for the delay to complete.
        delayTask.Wait();
        Console.WriteLine( "Deadlock.End" );
    }

    static void Main( string[] args )
    {
        var thread = new Thread( () => 
        {
            Console.WriteLine( "Thread.Start" );
            SynchronizationContext.SetSynchronizationContext( new DedicatedThreadSynchronisationContext() );
            Deadlock();
            Console.WriteLine( "Thread.End" );
        } );
        thread.Start();
        Console.WriteLine( "Thread.Join.Start" );
        thread.Join();
        Console.WriteLine( "Thread.Join.End" );
        Console.WriteLine( "Press any key to exit" );
        Console.ReadKey( true );
        Console.WriteLine( "Pressed" );
    }
}
Run Code Online (Sandbox Code Playgroud)

所以Deadlock()应该在正确的上下文中导致死锁.要模拟ASP.NET上下文,我正在使用来自/sf/answers/2219988081/的DedicatedThreadSynchronisationContext:

public sealed class DedicatedThreadSynchronisationContext : SynchronizationContext, IDisposable
{
    public DedicatedThreadSynchronisationContext()
    {
        m_thread = new Thread( ThreadWorkerDelegate );
        m_thread.Start( this );
    }

    public void Dispose()
    {
        m_queue.CompleteAdding();
    }

    /// <summary>Dispatches an asynchronous message to the synchronization context.</summary>
    /// <param name="d">The System.Threading.SendOrPostCallback delegate to call.</param>
    /// <param name="state">The object passed to the delegate.</param>
    public override void Post( SendOrPostCallback d, object state )
    {
        if ( d == null ) throw new ArgumentNullException( "d" );
        m_queue.Add( new KeyValuePair<SendOrPostCallback, object>( d, state ) );
    }

    /// <summary> As 
    public override void Send( SendOrPostCallback d, object state )
    {
        using ( var handledEvent = new ManualResetEvent( false ) )
        {
            Post( SendOrPostCallback_BlockingWrapper, Tuple.Create( d, state, handledEvent ) );
            handledEvent.WaitOne();
        }
    }

    public int WorkerThreadId { get { return m_thread.ManagedThreadId; } }
    //=========================================================================================

    private static void SendOrPostCallback_BlockingWrapper( object state )
    {
        var innerCallback = ( state as Tuple<SendOrPostCallback, object, ManualResetEvent> );
        try
        {
            innerCallback.Item1( innerCallback.Item2 );
        }
        finally
        {
            innerCallback.Item3.Set();
        }
    }

    /// <summary>The queue of work items.</summary>
    private readonly BlockingCollection<KeyValuePair<SendOrPostCallback, object>> m_queue =
        new BlockingCollection<KeyValuePair<SendOrPostCallback, object>>();

    private readonly Thread m_thread = null;

    /// <summary>Runs an loop to process all queued work items.</summary>
    private void ThreadWorkerDelegate( object obj )
    {
        SynchronizationContext.SetSynchronizationContext( obj as SynchronizationContext );

        try
        {
            foreach ( var workItem in m_queue.GetConsumingEnumerable() )
                workItem.Key( workItem.Value );
        }
        catch ( ObjectDisposedException ) { }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在调用Deadlock()之前设置了上下文:

SynchronizationContext.SetSynchronizationContext( new DedicatedThreadSynchronisationContext() );
Run Code Online (Sandbox Code Playgroud)

我希望代码挂在这一行上,因为它应该捕获上下文:

await Task.Delay( 1000 );
Run Code Online (Sandbox Code Playgroud)

然而,它传递得很好,程序运行到最后,它打印"按下".(虽然程序挂起在DedicatedThreadSynchronisationContext.ThreadWorkerDelegate()上,所以它不存在,但我认为这是一个小问题.)

为什么不产生死锁?模拟死锁的正确方法是什么?

========================================

编辑

按照Luaan的回答,

我使用DedicatedThreadSynchronisationContext.Send()而不是创建一个新线程:

        Console.WriteLine( "Send.Start" );
        var staContext = new DedicatedThreadSynchronisationContext();
        staContext.Send( ( state ) =>
        {
            Deadlock();
        }, null );
        Console.WriteLine( "Send.End" );
Run Code Online (Sandbox Code Playgroud)

它允许Deadlock()在上下文中运行,因此'await'捕获相同的上下文,从而发生死锁.

谢谢Luaan!

Lua*_*aan 4

因为它Deadlock与同步上下文不在同一线程上运行。

您需要确保Deadlock在同步上下文上运行 - 仅设置上下文并调用方法并不能确保这一点。

无需修改即可实现此目的的最简单方法是将Deadlock同步发送到同步上下文:

SynchronizationContext.Current.Send(_ => Deadlock(), null);
Run Code Online (Sandbox Code Playgroud)

这会给你一个很好的延迟任务等待死锁:)