问题描述
在后台线程中调用 saveFileDialog.ShowDialog()
时,出现以下异常:
I get the following exception when calling saveFileDialog.ShowDialog()
in a background thread:
根据:
Threading.Thread.CurrentThread.ApartmentState = Threading.ApartmentState.STA;
但是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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!