本文介绍了C#显示对话框线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Dialog Box(导入器),用于选择要导入到应用程序中的文件.此Dialog Box(导入器)还具有另一个对话框(文件),它是OpenFileDialog.

I have a Dialog Box (Importer) which i use for choosing a file I want to import into an app. This Dialog Box (Importer) also has another Dialog Box (File) which is an OpenFileDialog.

代码运行的是这样的

//Main File

if (Importer.ShowDialog == DialogResult.Ok){
// Start Import
}

//Importer File

OnDoubleClick of TextBox

if(File.ShowDialog == DialogResult.Ok){
// Find File
}

但是在第二个ShowDialog上,我总是遇到以下错误:

However on the Second ShowDialog I always get the following error:

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.

这是一个线程问题,我应该如何处理.

Is this a threading issue, and how should i deal with it.

我期待着您的回音.问候詹姆斯

I look forward to hearing from you.RegardsJames

-更新更多代码以提供帮助这一切都在第一个Form.ShowDialog()

--Update some more code to help This is all inside the first 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控件对话.

How do I stop the thread and update the text on screen. The thread only seems to be able to talk to varibles not UI controls.

推荐答案

要对其进行修复,请使用属性[STAThread]标记您的Program类的Main()方法.

To fix it mark your Main() method of Program class with attribute [STAThread].

后续阅读: CA2232:使用STAThread标记Windows窗体入口点.

在这种情况下,当然Main()方法是您的切入点,而不管框架是什么.

In this case of course Main() method is your entry point regardless of what framework does.

这篇关于C#显示对话框线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 15:52