async Task Main() + GUI
Hi,
I just noticed the very nice feature with async Task Main.
However, the following piece of code acts a little unexpected.
I would expect it to return to the execution context of the ui thread.
In comparison, this works:
Also is there a way to get the ui dispatcher so that one could dispatch work to the ui thread of the query? I noticed it is possible to just get the current dispatcher at the top of the query but that feels a little bit off for larger queries.
Thanks in advance.
I just noticed the very nice feature with async Task Main.
However, the following piece of code acts a little unexpected.
//[STAThread]
async Task Main()
{
await Task.Delay(TimeSpan.FromSeconds(1));// .ConfigureAwait(true);
new Button(){Content = "A"}.Dump();
}
I would expect it to return to the execution context of the ui thread.
In comparison, this works:
async Task Main()
{
var disp = Dispatcher.CurrentDispatcher;
await Task.Delay(TimeSpan.FromSeconds(1));//.ConfigureAwait(true);
disp.Invoke(() =>
{
new Button() {Content = "A"}.Dump();
});
}
Also is there a way to get the ui dispatcher so that one could dispatch work to the ui thread of the query? I noticed it is possible to just get the current dispatcher at the top of the query but that feels a little bit off for larger queries.
Thanks in advance.
Comments
You can do this by dumping a UI control before the first await, or by putting the following code at the start of your query:
Util.CreateSynchronizationContext();
Thanks again.
Is it possible to make it work with MTA threads?
You can make LINQPad use MTA threads in Edit | Preferences > Advanced, with the usual provisos of MTA threads.
I was asking if it possible to have
async
code with MTA threads and UI being properly dumped/displayed? Or if I need UI fromasync
code then I need to use STA threads?If you need a UI, you must stick with STA threads. Keep in mind that your choice of STA/MTA for queries applies only to the main query thread. Worker threads and pooled threads will still be MTA.
In other words, the following expression always returns MTA:
await Task.Run (() => Thread.CurrentThread.GetApartmentState())
Thanks for clarification.