gpt4 book ai didi

C# WinForms : How to set Main function STAThreadAttribute

转载 作者:IT王子 更新时间:2023-10-29 04:22:29 29 4
gpt4 key购买 nike

在后台线程中调用 saveFileDialog.ShowDialog() 时出现以下异常:

Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it.

根据 this :

To fix the problem, insert the statement:

Threading.Thread.CurrentThread.ApartmentState = Threading.ApartmentState.STA;

in Main right before the Application.Run statement.

但 Application.Run 语句位于 Program.cs 中,它似乎是生成的代码,因此任何更改都可能意外丢失。此外,我找不到在项目或主窗体属性中将当前线程设置为 STA 的方法,但也许我找错了地方。在后台线程中调用 saveFileDialog.ShowDialog() 的正确方法是什么?

最佳答案

解决方案非常简单;只需将其添加到 Main 方法之上 [STAThread]

所以你的主要方法应该是这样的

 [STAThread]
static void Main(string[] args)
{
....
}

它对我有用。

关于C# WinForms : How to set Main function STAThreadAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6373645/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com