【发布时间】:2014-03-17 09:42:11
【问题描述】:
我有一个Dialog Box(导入器),用于选择我想导入应用程序的文件。这个Dialog Box(进口商)还有另一个对话框(文件)是OpenFileDialog。
代码运行是这样的
//Main File
if (Importer.ShowDialog == DialogResult.Ok){
// Start Import
}
//Importer File
OnDoubleClick of TextBox
if(File.ShowDialog == DialogResult.Ok){
// Find File
}
但是在第二个ShowDialog 我总是收到以下错误:
An unhandled exception of type 'System.Threading.ThreadStateException' occurred in System.Windows.Forms.dll
Additional information: 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 exception is only raised if a debugger is attached to the process.
这是一个线程问题,我应该如何处理它。
我期待收到您的来信。 问候 詹姆斯
--更新一些代码来帮助这一切都在第一个Form.ShowDialog()里面
private void fileNametxt_DoubleClick(object sender, EventArgs e)
{
myth = new Thread(new System.Threading.ThreadStart(ChooseFile));
myth.ApartmentState = ApartmentState.STA;
myth.Start();
while(myth.ThreadState != ThreadState.Aborted || myth.ThreadState != ThreadState.Stopped)
{
fileNametxt.Text = FileName;
}
fileNametxt.Text = FileName;
}
private void ChooseFile()
{
openFileDialog.ShowDialog();
if (openFileDialog.FileName != "")
{
FileName = openFileDialog.FileName.Trim();
}
myth.Abort();
}
如何停止线程并更新屏幕上的文本。该线程似乎只能与变量而不是 UI 控件对话。
【问题讨论】:
-
签出this。
-
对话框是否从主线程显示?
-
程序员有逆向操作的诀窍。这样做的正确方法是在 UI 线程上显示对话框并在工作线程上运行导入代码。反过来做总是错误的,并且会产生像这样的运行时异常。还有更多的麻烦。使用 BackgroundWorker 或 Task 类来运行导入器。
-
您也应该包含其余代码。这并没有提供足够的线索来理解导致交叉线程问题的原因。
-
你为什么选择在远离主线程的地方显示对话框?
标签: c# multithreading dialog showdialog