开发者

STAThread missing, but it is there

开发者 https://www.devze.com 2023-01-13 16:05 出处:网络
Here is the error message that I am recieving when I try to open an OpenFileDialog in my program: \"Current thread must be set to single

Here is the error message that I am recieving when I try to open an OpenFileDialog in my program:

"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."

The problem with this error message is that my Main method DOES have the STAThread attribute attached to it开发者_C百科. I am at a loss as to how to handle this. How can I add something if it is already there. Doubling it up is not a good option, and I tried erasing it, building the app, adding it and building it again with no success. I just don't understand.

private void btnOldFind_Click(object sender, EventArgs e)
{
     openFileDialog1.Multiselect = false;
     openFileDialog1.FileName = "";
     openFileDialog1.ShowHelp = false;
     openFileDialog1.AutoUpgradeEnabled = true;
     openFileDialog1.InitialDirectory = @"C:\";
     openFileDialog1.Filter = "Microsoft Installer (*.msi)|*.msi|All Files (*.*)|*.* ";
     openFileDialog1.FilterIndex = 1;
     openFileDialog1.RestoreDirectory = true;

     if (openFileDialog1.ShowDialog() == DialogResult.OK)
     {
         textBoxOldInstallation.Text = openFileDialog1.FileName;
     }
}

and the main method is:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

And no threading is done explicitly. Just a pretty basic program to be honest.

EDIT2::

Here is the complete error message including call stack

System.Threading.ThreadStateException was unhandled Message="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." Source="System.Windows.Forms" StackTrace: at System.Windows.Forms.FileDialog.RunDialog(IntPtr hWndOwner) at System.Windows.Forms.CommonDialog.ShowDialog(IWin32Window owner) at System.Windows.Forms.CommonDialog.ShowDialog() at MSI_Comparison_GUI.Form1.btnOldFind_Click(Object sender, EventArgs e) in c:\tfs\DocuWare .NET\DocuWare NewGen\src\Tools\MSI_Comparison\MSI_Comparison_GUI\Form1.cs:line 70 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at MSI_Comparison_GUI.Program.Main() in c:\tfs\DocuWare .NET\DocuWare NewGen\src\Tools\MSI_Comparison\MSI_Comparison_GUI\Program.cs:line 18 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException:


It might be that you are facing the following problem reported on Connect1:

.vshost.exe forces wrong threading model used when debugging a .exe if a .dll of the same name exists in same bin directory

According to that issue it happens that the hosting process of Visual Studio, i.e. the myprogram.vshost.exe enforces the wrong apartment state when you have both a myprogram.exe and a myprogram.dll file in your output folder.

The problem might be specific to some older version of Visual Studio (2005), and I haven't been able to reproduce it using VS 2010.

The obvious workaround would be to change the name of the dll or to move the dll to another folder.

The situation might have come up because you changed the output type of your project from class libary to Windows application.

1It is unclear whether this problem is confirmed by Microsoft or not, it just says that the problem is outside the responsibility of the VS product team.


You've got an impossible stack trace. It is clear that threading is not the cause of the problem, everything is running on the main thread and the [STAThread] attribute on your Main method is setting the apartment state. The stack trace shows that it indeed the entrypoint.

Well, bad news, some kind of add-on is farking with your main thread. Doing something nasty like calling CoUninitialize too many times. I've had this happen to me once, took me a month to find it. Start diagnosing this with Project + Properties, Debug tab, tick "Enable unmanaged code debugging". That lets you see what DLLs are getting loaded into your program, it is shown in the Output window.

The first lead is when the dialog displays okay the first time but fails the second time. Then you've got some kind of shell extension handler that wormed its way into your program. Use SysInternals' AutoRuns utility and disable any shell extension handler that wasn't made by Microsoft.

It gets harder when the dialog fails right away. Then use Debug + Windows + Modules and go through the list of DLLs. Pay attention to where they came from, shown in the Path column. Distrust anything the doesn't quack like a .NET or Microsoft DLL. Especially not having a Symbol File when you enabled the Microsoft Symbol Server is a lead. A good way to make some headway with this is to compare that list to one you see on another machine that doesn't have this problem.

I do have a war-story about this. My COM code was crashing on hundreds of machines, all I had to go by was a minidump. Took me a month to discover the source, an open source project named ffdshow. Very widely distributed, using different names as well. It had a bug, calling CoUnitialize two times too many. The bug was present in releases for two years but got fixed about a year and a half ago. Very hard to diagnose, I didn't get close to it until I started looking at old releases. If you do see ffdshow in your Modules window then you're close :)

Good luck, let us know the evil-doer.


Can't say without code. If a console app, add the following before you call the method:

Console.Write(System.Threading.Thread.CurrentThread.ApartmentState);

otherwise,

MessageBox.Show(System.Threading.Thread.CurrentThread.ApartmentState);

and see what the threading apartment state REALLY is.


Try setting breakpoints at the main procedure, the point where the dialogbox is created, and where it is used. Then look at what thread(s) you actually are in. Also, check what the value of Thread.CurrentThread.GetApartmentState() is at those points.


t.SetApartmentState(ApartmentState.STA);

The above line of code worked for me. once try it.

0

精彩评论

暂无评论...
验证码 换一张
取 消