【问题标题】:Calling TaskCompletionSource.SetResult in a non blocking manner以非阻塞方式调用 TaskCompletionSource.SetResult
【发布时间】:2013-10-29 04:53:44
【问题描述】:

我发现TaskCompletionSource.SetResult(); 在返回之前调用了等待任务的代码。就我而言,这会导致死锁。

这是一个以普通Thread开头的简化版

void ReceiverRun()
    while (true)
    {
        var msg = ReadNextMessage();
        TaskCompletionSource<Response> task = requests[msg.RequestID];

        if(msg.Error == null)
            task.SetResult(msg);
        else
            task.SetException(new Exception(msg.Error));
    }
}

代码的“异步”部分看起来像这样。

await SendAwaitResponse("first message");
SendAwaitResponse("second message").Wait();

Wait 实际上嵌套在非异步调用中。

SendAwaitResponse(简体)

public static Task<Response> SendAwaitResponse(string msg)
{
    var t = new TaskCompletionSource<Response>();
    requests.Add(GetID(msg), t);
    stream.Write(msg);
    return t.Task;
}

我的假设是第二个 SendAwaitResponse 将在 ThreadPool 线程中执行,但它会在为 ReceiverRun 创建的线程中继续。

有没有办法在不继续等待的代码的情况下设置任务的结果?

该应用程序是一个控制台应用程序。

【问题讨论】:

  • 一个非常简单的解决方法是使用Task.Run(() =&gt; task.SetResult(msg));(同样使用SetException())。但我希望有更好的选择。
  • 这篇 2018 年的博文详细讨论了该问题和解决方法:devblogs.microsoft.com/premier-developer/…

标签: c# multithreading asynchronous task-parallel-library async-await


【解决方案1】:

我发现 TaskCompletionSource.SetResult();在返回之前调用等待任务的代码。就我而言,这会导致死锁。

是的,我有一个 blog post 记录这个(AFAIK 它没有记录在 MSDN 上)。发生死锁是因为两件事:

  1. async 和阻塞代码混合在一起(例如,async 方法正在调用 Wait)。
  2. 使用TaskContinuationOptions.ExecuteSynchronously 安排任务继续。

我建议从最简单的解决方案开始:删除第一件事 (1)。即,不要混用 async 和 Wait 调用:

await SendAwaitResponse("first message");
SendAwaitResponse("second message").Wait();

相反,始终使用await:

await SendAwaitResponse("first message");
await SendAwaitResponse("second message");

如果需要,您可以在调用堆栈更上方的替代点上Wait(不是在async 方法中)。

这是我最推荐的解决方案。但是,如果您想尝试删除第二件事 (2),您可以采取一些技巧:将 SetResult 包装在 Task.Run 中以将其强制到单独的线程上(我的 AsyncEx library 有 *WithBackgroundContinuations执行此操作的扩展方法),或为您的线程提供实际上下文(例如我的AsyncContext type)并指定ConfigureAwait(false),这将是cause the continuation to ignore the ExecuteSynchronously flag。

但这些解决方案比仅仅将async 和阻塞代码分开要复杂得多。

作为旁注,请查看TPL Dataflow;听起来您可能会觉得它很有用。

【讨论】:

  • 将 SetResult 包装在 Task.Run 中有效!为了设置上下文看起来很有趣,我会研究一下。调用 SendAwaitResponse 的代码可能不受我控制,因此我的目标是让 ReceiverRun 继续传递消息,即使单个等待继续决定使用 Wait 或任何其他耗时的操作。
  • 现在还有 TaskCreationOptions.RunContinuationsAsynchronously 方法允许您指定(在 TaskCompletionSource 构造函数中)应异步执行延续。但是,它只是 .NET 4.6+。
  • SetResult 应该只是将任务标记为完成,并且只要线程池线程可用,它的延续就应该运行。如果 SetResult 阻止等待该事件发生,则应将其作为严重错误提交。
  • @Triynko:我reported it as a bug 7 年前。 IIRC,它被“按设计”关闭。
  • If SetResult is blocking waiting on that to happen 这也吸引了我。 7 岁的设计错误 aaaw..
【解决方案2】:

由于您的应用是控制台应用,它在默认的synchronization context 上运行,其中await 延续回调将在等待任务已完成的同一线程上调用。如果你想在await SendAwaitResponse之后切换线程,你可以通过await Task.Yield()来实现:

await SendAwaitResponse("first message");
await Task.Yield(); 
// will be continued on a pool thread
// ...
SendAwaitResponse("second message").Wait(); // so no deadlock

您可以通过将Thread.CurrentThread.ManagedThreadId 存储在Task.Result 中并将其与await 之后的当前线程ID 进行比较来进一步改进这一点。如果您仍然在同一个线程上,请执行await Task.Yield()。

虽然我知道SendAwaitResponse 是您实际代码的简化版本,但它内部仍然是完全同步的(您在问题中展示的方式)。为什么你会期望那里有任何线程切换?

无论如何,您可能应该重新设计您的逻辑,使其不假设您当前处于哪个线程。避免混合await 和Task.Wait() 并使所有代码异步。通常,可以在顶层某处仅使用一个Wait()(例如在Main 内部)。

[EDITED] 从ReceiverRun 调用task.SetResult(msg) 实际上将控制流转移到await 在task 上的点 - 因为默认同步,没有线程切换上下文的行为。因此,执行实际消息处理的代码正在接管ReceiverRun 线程。最终,SendAwaitResponse("second message").Wait() 在同一个线程上被调用,导致死锁。

以下是控制台应用程序代码,以您的示例为蓝本。它在ProcessAsync 中使用await Task.Yield() 在单独的线程上安排继续,因此控制流返回到ReceiverRun 并且没有死锁。

using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    class Program
    {
        class Worker
        {
            public struct Response
            {
                public string message;
                public int threadId;
            }

            CancellationToken _token;
            readonly ConcurrentQueue<string> _messages = new ConcurrentQueue<string>();
            readonly ConcurrentDictionary<string, TaskCompletionSource<Response>> _requests = new ConcurrentDictionary<string, TaskCompletionSource<Response>>();

            public Worker(CancellationToken token)
            {
                _token = token;
            }

            string ReadNextMessage()
            {
                // using Thread.Sleep(100) for test purposes here,
                // should be using ManualResetEvent (or similar synchronization primitive),
                // depending on how messages arrive
                string message;
                while (!_messages.TryDequeue(out message))
                {
                    Thread.Sleep(100);
                    _token.ThrowIfCancellationRequested();
                }
                return message;
            }

            public void ReceiverRun()
            {
                LogThread("Enter ReceiverRun");
                while (true)
                {
                    var msg = ReadNextMessage();
                    LogThread("ReadNextMessage: " + msg);
                    var tcs = _requests[msg];
                    tcs.SetResult(new Response { message = msg, threadId = Thread.CurrentThread.ManagedThreadId });
                    _token.ThrowIfCancellationRequested(); // this is how we terminate the loop
                }
            }

            Task<Response> SendAwaitResponse(string msg)
            {
                LogThread("SendAwaitResponse: " + msg);
                var tcs = new TaskCompletionSource<Response>();
                _requests.TryAdd(msg, tcs);
                _messages.Enqueue(msg);
                return tcs.Task;
            }

            public async Task ProcessAsync()
            {
                LogThread("Enter Worker.ProcessAsync");

                var task1 = SendAwaitResponse("first message");
                await task1;
                LogThread("result1: " + task1.Result.message);
                // avoid deadlock for task2.Wait() with Task.Yield()
                // comment this out and task2.Wait() will dead-lock
                if (task1.Result.threadId == Thread.CurrentThread.ManagedThreadId)
                    await Task.Yield();

                var task2 = SendAwaitResponse("second message");
                task2.Wait();
                LogThread("result2: " + task2.Result.message);

                var task3 = SendAwaitResponse("third message");
                // still on the same thread as with result 2, no deadlock for task3.Wait()
                task3.Wait();
                LogThread("result3: " + task3.Result.message);

                var task4 = SendAwaitResponse("fourth message");
                await task4;
                LogThread("result4: " + task4.Result.message);
                // avoid deadlock for task5.Wait() with Task.Yield()
                // comment this out and task5.Wait() will dead-lock
                if (task4.Result.threadId == Thread.CurrentThread.ManagedThreadId)
                    await Task.Yield();

                var task5 = SendAwaitResponse("fifth message");
                task5.Wait();
                LogThread("result5: " + task5.Result.message);

                LogThread("Leave Worker.ProcessAsync");
            }

            public static void LogThread(string message)
            {
                Console.WriteLine("{0}, thread: {1}", message, Thread.CurrentThread.ManagedThreadId);
            }
        }

        static void Main(string[] args)
        {
            Worker.LogThread("Enter Main");
            var cts = new CancellationTokenSource(5000); // cancel after 5s
            var worker = new Worker(cts.Token);
            Task receiver = Task.Run(() => worker.ReceiverRun());
            Task main = worker.ProcessAsync();
            try
            {
                Task.WaitAll(main, receiver);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            Worker.LogThread("Leave Main");
            Console.ReadLine();
        }
    }
}

这与在ReceiverRun 中执行Task.Run(() =&gt; task.SetResult(msg)) 没有太大区别。我能想到的唯一优点是您可以明确控制何时切换线程。这样,您可以尽可能长时间地停留在同一个线程上(例如,对于task2、task3、task4,但在task4 之后仍然需要另一个线程切换以避免task5.Wait() 上的死锁)。

这两种解决方案最终都会使线程池增长,这在性能和可扩展性方面都很糟糕。

现在,如果我们在上面的代码中将await task 中的任何地方替换为await task,我们就不必使用await Task.Yield,仍然不会出现死锁。但是,ProcessAsync 内部第一个 await task1 之后的整个 await 调用链实际上将在 ReceiverRun 线程上执行。只要我们不使用其他 Wait() 风格的调用阻塞这个线程,并且在我们处理消息时不做大量 CPU 绑定的工作,这种方法可能工作正常(异步 IO 绑定 await -style 调用仍然应该没问题,它们实际上可能会触发隐式线程切换)。

也就是说,我认为您需要一个安装了序列化同步上下文的单独线程来处理消息(类似于WindowsFormsSynchronizationContext)。这就是包含awaits 的异步代码应该运行的地方。您仍然需要避免在该线程上使用Task.Wait。如果单个消息处理需要大量 CPU 密集型工作,您应该使用 Task.Run 进行此类工作。对于异步 IO 绑定调用,您可以留在同一个线程上。

您可能想查看@StephenCleary 中的ActionDispatcher/ActionDispatcherSynchronizationContext Nito Asynchronous Library 用于您的异步消息处理逻辑。希望斯蒂芬能够加入并提供更好的答案。

【讨论】:

    【解决方案3】:

    “我的假设是第二个 SendAwaitResponse 将在 ThreadPool 线程中执行,但它会在为 ReceiverRun 创建的线程中继续。”

    这完全取决于您在 SendAwaitResponse 中执行的操作。异步和并发are not the same thing.

    签出:C# 5 Async/Await - is it *concurrent*?

    【讨论】:

    • 我补充说我的应用程序是一个控制台应用程序,但最佳答案仍然表明它将在线程池线程中继续,这并没有发生。
    • Stream.Write 是同步方法,你可能想使用 WriteAsync
    • @Slugart 当然可以,但是使用 WriteAsync() 并不能解决问题。
    【解决方案4】:

    聚会有点晚了,但这是我认为有价值的解决方案。

    我也一直在努力解决这个问题,我通过在等待的方法上捕获 SynchronizationContext 来解决它。

    它看起来像:

    // just a default sync context
    private readonly SynchronizationContext _defaultContext = new SynchronizationContext();
    
    void ReceiverRun()
    {
        while (true)    // <-- i would replace this with a cancellation token
        {
            var msg = ReadNextMessage();
            TaskWithContext<TResult> task = requests[msg.RequestID];
    
            // if it wasn't a winforms/wpf thread, it would be null
            // we choose our default context (threadpool)
            var context = task.Context ?? _defaultContext;
    
            // execute it on the context which was captured where it was added. So it won't get completed on this thread.
            context.Post(state =>
            {
                if (msg.Error == null)
                    task.TaskCompletionSource.SetResult(msg);
                else
                    task.TaskCompletionSource.SetException(new Exception(msg.Error));
            });
        }
    }
    
    public static Task<Response> SendAwaitResponse(string msg)
    {
        // The key is here! Save the current synchronization context.
        var t = new TaskWithContext<Response>(SynchronizationContext.Current); 
    
        requests.Add(GetID(msg), t);
        stream.Write(msg);
        return t.TaskCompletionSource.Task;
    }
    
    // class to hold a task and context
    public class TaskWithContext<TResult>
    {
        public SynchronizationContext Context { get; }
    
        public TaskCompletionSource<TResult> TaskCompletionSource { get; } = new TaskCompletionSource<Response>();
    
        public TaskWithContext(SynchronizationContext context)
        {
            Context = context;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多