ThreadStateException错误:ShowDialog()

时间:2014-04-10 15:33:05

标签: c# wpf visual-studio-2010 c#-4.0

我写了一个client.cs,当服务器告诉我们时,它会在一个新线程中打开一个电子表格:

client.cs

if (!isSpreadsheetOpen)
                        {
                            isSpreadsheetOpen= true;
                            GUI = new Form1(ClientStringSocket);
                            connectedToServer = true;
                            var thread = new System.Threading.Thread(delegate()
                            {
                                Application.EnableVisualStyles();
                                Application.SetCompatibleTextRenderingDefault(false);
                                DemoApplicationContext appContext = DemoApplicationContext.getAppContext();
                                appContext.RunForm(GUI);
                                Application.Run(appContext);
                            });
                            thread.Start();
                        }

当用户单击“保存”按钮时,将弹出如下图所示的对话框。

if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                spreadsheet.Save(saveFileDialog1.FileName);
            }

enter image description here

但是,我收到了这个错误。

ThreadStateExcepton: 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.

我尝试添加[STAThread]无济于事。如何解决此错误?

2 个答案:

答案 0 :(得分:2)

该表单将在服务器上弹出,而不是在客户端上弹出。在ASP应用程序中创建新的winform是错误的。不要这样做。

答案 1 :(得分:1)

我可以通过在启动线程之前添加这两行来解决此问题:

                            thread.IsBackground = true;
                            thread.SetApartmentState(ApartmentState.STA);
                            thread.Start();