The solution of using thread to report error in openfiledialog in. Net

Time:2020-2-20

Yesterday, when making a small npoi read demo, use openfiledialog to open the file. The first writing method is to write directly in the event of clicking the button, and an error will be reported. The code is as follows:

OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Microsoft Office Excel(*.xls;*.xlsx)|*.xls;*.xlsx";
ofd.FilterIndex = 1;
ofd.RestoreDirectory = true;


if (ofd.ShowDialog() == DialogResult.OK)
{
   //Check whether the open file path is an empty address
   if (!string.IsNullOrEmpty(ofd.FileName))
   {
          ReadFromExcelFile(ofd.FileName);
   }
   else
   {
          This.textbox1.text = "please open excel file";
    }
}

Or directly


using(OpenFileDialog ofd = new OpenFileDialog()){ ofd.ShowDialog(); }

These two methods, no matter which one is written, will report an error when the code is executed. The specific error is:

Unhandled exception of type ‘system. Threading. Threadstateexception’ occurred in system.windows.forms.dll

Additional information: before ole can be called, the current thread must be set to single thread unit (STA) mode. Make sure your main function is marked with stathreadattribute. This exception will only be thrown if the debugger is attached to the process. 

In this case, online query means that there is a thread problem, which is a thread conflict. I don’t know which one to execute. The specific statement is as follows:

There are three kinds of thread models provided by COM: single thread apartment (STA single thread apartment), multithreaded apartment (MTA multi thread apartment) and Central Apartment / thread neutral apartment / neutral thread apartment (Na / TNA / NTA neutral thread apartment, provided by COM +).

Sta can only be accessed by one thread, which is equivalent to the message loop of windows. The implementation mode is also through the message loop. ActiveX control, Ole document server and other interfaces use sta suite. MTA an object can be accessed by multiple threads, that is to say, the code of this object implements thread protection in its own methods to ensure that it can change its state correctly.

So when creating and accessing an ActiveX or OLE object, you must set the thread mode to sta.

Then, how to use openfiledialog in the sub thread to avoid such an error? Here is the changed code:

/// <summary>
    ///Single thread opening excel document
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btnXlx_Click(object sender, EventArgs e)
    {
      this.textBox1.Text = string.Empty;

      System.Threading.Thread s = new System.Threading.Thread(new System.Threading.ThreadStart(getExcel));
      s.ApartmentState = System.Threading.ApartmentState.STA;
      s.Start();

    }

    /// <summary>
    ///Read excel document address
    /// </summary>
    private void getExcel()
    {
      OpenFileDialog ofd = new OpenFileDialog();
      ofd.Filter = "Microsoft Office Excel(*.xls;*.xlsx)|*.xls;*.xlsx";
      ofd.FilterIndex = 1;
      ofd.RestoreDirectory = true;


      if (ofd.ShowDialog() == DialogResult.OK)
      {
        //Check whether the open file path is an empty address
        if (!string.IsNullOrEmpty(ofd.FileName))
        {
          ReadFromExcelFile(ofd.FileName);
        }
        else
        {
          This.textbox1.text = "please open excel file";
        }
      }
    }

It is to separate the content of thread execution and form a method separately, and then write the execution sub thread single thread execution statement in the event. In this case, there will be no error reporting that kind of thread exception.

PS: personal search online content, summed up, feel can be a solution, add [stathread] to other functions, such as main function, there are other ways, but they do not solve the problem. Personal methods may be troublesome in the eyes of the God. If the God has better methods, we will be very grateful and welcome to share here!

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.