In a GUI application, there are a ton of ways to run asynchronous code and have the result run on your "main" thread:
- Use
async
/await
- Use a
BackgroundWorker
someControl.Invoke()
.ContinueWith(..., TaskScheduler.FromCurrentSynchronizationContext())
etc. etc.
However, none of these options work in a console application because there is no synchronization context or GUI run-loop.
I'm modifying a console project which has its own manual run-loop. Something like this:
while (!cancelled)
{
if(api.HasMessage())
{
api.HandleMessage();
}
Thread.Sleep(1);
}
I'd like to be able to make asynchronous web-requests in this project, while still handling the results on the main run-loop thread to avoid typical multi-threading issues. Of course I could do this manually using queues, but it would be nice to be able to use async
/await
or one of the other paradigms which handles this much nicer.
Is there a method I can call from the run-loop to make this possible? I'm imagining something like, say, Thread.ResolveCurrentAwaitingTasks()
.