Say you're writing a custom single threaded GUI library (or anything with an event loop). From my understanding, if I use async/await
, or just regular TPL continuations, they will all be scheduled on TaskScheduler.Current
(or on SynchronizationContext.Current
).
The problem is that the continuation might want to access the single threaded parts of the library, which means it has to execute in the same event loop. For example, given a simple game loop, the events might be processed like this:
// 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();
}
Now given my assumption is correct and TPL uses the SynchronizationContext.Current
, any code in the application should be able to do something like this:
async void Foo() {
someLabel.Text = "Processing";
await BackgroundTask();
// This has to execute on the main thread
someLabel.Text = "Done";
}
Which brings me to the question. How do I implement a custom SynchronizationContext
that would allow me to handle continuations on my own thread? Is this even the correct approach?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…