【问题标题】:C# Show Dialog threadingC# 显示对话框线程
【发布时间】: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


【解决方案1】:

要修复它,请使用属性[STAThread] 标记Program 类的Main() 方法。

后续阅读:CA2232: Mark Windows Forms entry points with STAThread.

在这种情况下当然Main()方法你的入口点,不管框架做什么。

【讨论】:

  • 嗨@Migol,你知道它是如何与网络表单一起使用的吗?
【解决方案2】:

在这个错误中。构建解决方案不会引发错误,但调试会引发该错误。 我尝试创建新的解决方案并将令人兴奋的项目添加到新的解决方案中。错误已修复!

【讨论】:

    猜你喜欢
    • 2011-11-05
    • 2012-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多