【问题标题】:How to wrap a multithreaded callback for async/await?如何为异步/等待包装多线程回调?
【发布时间】:2018-02-17 14:26:54
【问题描述】:

我有 async/await 代码并想使用类似于 websocket 的 API。它需要一个回调来接收从另一个线程调用的新消息。

我可以在与连接启动相同的异步/等待上下文中执行此回调而不使用锁定吗?

我认为这就是 SynchronizationContext 的用途,但我不知道它是否是线程安全的。如果我记录线程 ID,每个回调将在不同的线程上。如果我记录 Task.CurrentId 它为空。我认为相同的同步上下文会在不同的线程中移动,所以这可能没问题,但我不知道如何确认。

// External api, the callbacks will be from multiple threads
public class Api
{
    public static Connect(
        Action<Connection> onConnect,
        Action<Connection> onMessage) 
    {}
}

async Task<Connection> ConnectAsync(Action<Message> callback)
{
    if (SynchronizationContext.Current == null)
    {
        SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
    }

    var syncContext = SynchronizationContext.Current;

    var tcs = new TaskCompletionSource<Connection>();

    // use post() to ensure callbacks from other threads are executed thread-safely

    Action<Connection> onConnect = conn => 
    {
        syncContext.Post(o => tcs.SetResult(conn), null);
    };
    Action<Message> onMsg = msg => 
    { 
        syncContext.Post(o => callback(msg), null);
    };

    // call the multi-threaded non async/await api supplying the callbacks

    Api.Connect(onConnect, onMsg);

    return await tcs.Task;
}

var connection = await ConnectAsync(
    msg => 
    { 
        /* is code here threadsafe with the send without extra locking? */ 
    });

await connection.Send("Hello world);

【问题讨论】:

  • 我不明白你想做什么,但可以说 Posting to SynchronizationContext(到你在代码中使用的这个特定的,如果 SynchronizationContext.Current 为空)只会执行线程池线程回调,仅此而已。
  • 在同一上下文中对 Post() 的多次调用是否可以并行执行,或者即使它们不在同一个线程上也可以保证它们是串行的?
  • 在这个特定的上下文中(基本的SynchronizationContext 你用SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()) 设置) - 发布只是将回调调度到线程池线程,仅此而已,没有其他任何事情要做。所以是的 - 回调将并行执行。在其他可能不同的情况下。
  • 我明白了。所以这意味着 UI 线程正在封装一个线程并实现一个消息泵作为它们的 SynchronisationContext 但这个不是。
  • 是的,没错。我会说你的图书馆不应该关心这些事情。在后台线程上执行回调是常见的做法,调用者应该自己处理。

标签: c# multithreading async-await synchronizationcontext


【解决方案1】:

感谢@Evk,他指出默认的 SynchronizationContext 实际上并没有同步任何内容或以您期望的方式实现发送/发布。

https://github.com/StephenClearyArchive/AsyncEx.Context

解决方法是使用 Stephen Cleary 的异步库,该库将 SynchronizationContext 实现为单个线程中的消息泵,以便在与其他等待调用相同的线程中调用 post() 调用。

// External api, the callbacks will be from multiple threads
public class Api
{
    public static Connect(
        Action<Connection> onConnect,
        Action<Connection> onMessage) 
    {}
}

async Task<Connection> ConnectAsync(Action<Message> callback)
{
    var syncContext = SynchronizationContext.Current;

    var tcs = new TaskCompletionSource<Connection>();

    // use post() to ensure callbacks from other threads are executed thread-safely

    Action<Connection> onConnect = conn => 
    {
        syncContext.Post(o => tcs.SetResult(conn), null);
    };
    Action<Message> onMsg = msg => 
    { 
        syncContext.Post(o => callback(msg), null);
    };

    // call the multi-threaded non async/await api supplying the callbacks

    Api.Connect(onConnect, onMsg);

    return await tcs.Task;
}

//
// https://github.com/StephenClearyArchive/AsyncEx.Context
//
Nito.AsyncEx.AsyncContext.Run(async () =>
{
    var connection = await ConnectAsync(
        msg => 
        { 
            /* this will execute in same thread as ConnectAsync and Send */ 
        });

    await connection.Send("Hello world);

    ... more async/await code
});

【讨论】:

    猜你喜欢
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 2021-06-30
    • 2012-05-04
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多