我遇到一个奇怪的情况,我得到以下异常,我用c#7.1运行一些测试代码
"调用线程必须是STA,因为许多UI组件都需要这样做。"
以下是抛出异常的代码:
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();
}
我确保MainThread是调用以下行的线程:
MainWindow mw = new MainWindow() is the main thread(this is the line that throws the above exception).
奇怪
我将主要功能的签名更改为:
[STAThread]
public static void Main()
没有例外,代码工作正常。有人可以告知为什么会这样吗?
Ps:我看过this link with the same exception,但在我的情况下没用。另外,我正在使用VS2017