相关疑难解决方法(0)

如何创建自定义SynchronizationContext,以便我自己的单线程事件循环可以处理所有延续?

假设您正在编写自定义单线程GUI库(或带有事件循环的任何内容).根据我的理解,如果我使用async/await,或只是常规的TPL延续,他们将全部安排在TaskScheduler.Current(或上SynchronizationContext.Current).

问题是延续可能想要访问库的单线程部分,这意味着它必须在同一个事件循环中执行.例如,给定一个简单的游戏循环,事件可能会像这样处理:

// All continuation calls should be put onto this queue
Queue<Event> events;

// The main thread calls the `Update` method continuously on each "frame"
void Update() {
    // All accumulated events are processed in order and the queue is cleared
    foreach (var event : events) Process(event);

    events.Clear();
}
Run Code Online (Sandbox Code Playgroud)

现在假设我的假设是正确的并且TPL使用了SynchronizationContext.Current,应用程序中的任何代码都应该能够执行以下操作:

async void Foo() {
    someLabel.Text = "Processing";

    await BackgroundTask();

    // This has to execute on the main thread
    someLabel.Text = "Done"; …
Run Code Online (Sandbox Code Playgroud)

c# multithreading asynchronous async-await

8
推荐指数
1
解决办法
2680
查看次数

标签 统计

async-await ×1

asynchronous ×1

c# ×1

multithreading ×1