C# Show Dialog threading

WJProctor picture WJProctor · Mar 17, 2014 · Viewed 11.2k times · Source

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.

The code runs something like this

//Main File

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

//Importer File

OnDoubleClick of TextBox

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

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. Regards James

--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();

    }

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.

Answer

Migol picture Migol · Mar 17, 2014

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

Follow-up reading: CA2232: Mark Windows Forms entry points with STAThread.

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