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

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

问题描述

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

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


当前线程必须设置为单
线程单元(STA)模式,然后才能进行OLE
调用。确保
Main函数上已标记STAThreadAttribute

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.

根据


要解决此问题,请插入
语句:

To fix the problem, insert the statement:



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




位于Main中,位于
Application.Run语句之前。

in Main right before the Application.Run statement.

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

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()不应从后台线程调用-使用Invoke(..)。

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

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

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

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