C# WinForms:如何设置主函数 STAThreadAttribute [英] C# WinForms: How to set Main function STAThreadAttribute

查看:23
本文介绍了C# WinForms:如何设置主函数 STAThreadAttribute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<块引用>

当前线程必须设置为单线程OLE 之前的线程单元 (STA) 模式可以拨打电话.确保您的主函数有 STAThreadAttribute标记在上面.

根据这个:

<块引用>

要解决问题,请插入声明:

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

<块引用>

在 Main 之前Application.Run 语句.

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

解决方案

不应从后台线程调用 ShowDialog() - 使用 Invoke(..).

Invoke((Action)(() => { saveFileDialog.ShowDialog() }));

I get the following exception when calling saveFileDialog.ShowDialog() in a background thread:

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.

According to this:

To fix the problem, insert the statement:

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

in Main right before the Application.Run statement.

But the Application.Run statement is in Program.cs which seems to be generated code so any changes might be unexpectedly lost. Also, I could not find a way to set current thread to STA in the project or main form properties but maybe I am looking in the wrong place. What is the proper way to call saveFileDialog.ShowDialog() in a background thread?

解决方案

ShowDialog() shouldn't be called from a background thread - use Invoke(..).

Invoke((Action)(() => { saveFileDialog.ShowDialog() }));

这篇关于C# WinForms:如何设置主函数 STAThreadAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆