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

时间:2016-10-31 13:51:43

标签: 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" );
    }
}

所以死锁()应该会在正确的上下文中导致死锁。 为了模拟ASP.NET上下文,我使用https://stackoverflow.com/a/31714115/121240中的 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 ) { }
    }
}

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

SynchronizationContext.SetSynchronizationContext( new DedicatedThreadSynchronisationContext() );

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

await Task.Delay( 1000 );

但是,它传递得很好,程序会一直运行到最后,并打印出“Pressed”。 (虽然程序挂起在DedicatedThreadSynchronisationContext.ThreadWorkerDelegate()上,所以它不存在,但我认为这是一个小问题。)

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

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

修改

按照Luaan的回答,

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

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

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

谢谢Luaan!

2 个答案:

答案 0 :(得分:3)

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

您需要确保在同步上下文中运行Deadlock - 只需设置上下文并调用方法无法确保。

通过少量修改完成此操作的最简单方法是将Deadlock同步发送到同步上下文:

SynchronizationContext.Current.Send(_ => Deadlock(), null);

这为延迟任务等待提供了一个很好的死锁:)

答案 1 :(得分:0)

您正在使用的同步上下文是创建一个新线程并将所有工作发送给该线程完成,因此您阻止设置同步上下文的线程这一事实无关紧要这不是正在开展工作的主题。

如果你想要死锁,你需要安排一个回调来使用那个同步上下文,然后阻止那里,当还需要额外的回调来继续它。或者,您可以使用在启动它的线程中运行的更传统的消息循环,而不是以静默方式创建新的消息循环。