我需要一个自定义的SynchronizationContext:
我需要这个,所以我可以单独测试一些线程代码,它们将在实际应用程序中与WinForm对话.
在我自己编写之前,我希望有人可以指出我的简单(和小)实现.
假设您正在编写自定义单线程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)