I am facing a strange situation where I am getting the following exception, I was running some test code with c# 7.1
"The calling thread must be STA, because many UI components require this."
Here is the code which throws the exception :
public async Task StartAsync()
{
try
{
await Task.Yield();
MainWindow mw = new MainWindow();
mw.Show();
mw.Activate();
}
catch (Exception exp)
{
int why= 0;
}
}
[STAThread]
public static async Task Main()
{
var application = new AppNoUri() { ShutdownMode = ShutdownMode.OnExplicitShutdown };
SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext());
application.Dispatcher.UnhandledException += Dispatcher_UnhandledException;
application.InitializeComponent();
Program p = new Program();
p.StartAsync();
application.Run();
}
I have made sure that the MainThread is the thread calling the below line:
MainWindow mw = new MainWindow() is the main thread(this is the line that throws the above exception).
Strangely
I change the signature of the main function to:
[STAThread]
public static void Main()
There is no exception and the code works fine. Can someone please advise as to why the case ?
Ps: I have seen this link with the same exception and but it was not helpful in my case. Also, I am using VS2017