【问题标题】:System.InvalidOperationException in vs 2005VS 2005 中的 System.InvalidOperationException
【发布时间】:2010-07-06 11:44:55
【问题描述】:

我使用 dotnetmagic 库并创建了一个可停靠窗口,当从 IDE 运行时 (VS2005) 有效,但是当我使用可执行文件时,它会引发异常,内容如下:

System.InvalidOperationException: DragDrop registration did not succeed. ---> 
System.Threading.ThreadStateException: 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.
   at System.Windows.Forms.Control.SetAcceptDrops(Boolean accept)
   --- End of inner exception stack trace ---
   at System.Windows.Forms.Control.SetAcceptDrops(Boolean accept)
   at System.Windows.Forms.Control.OnHandleCreated(EventArgs e)
   at System.Windows.Forms.Control.WmCreate(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
   at System.Windows.Forms.ContainerControl.WndProc(Message& m)
   at System.Windows.Forms.UserControl.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.Callback(
       IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

如何剪掉这些东西,谁能帮我解决这个问题?

【问题讨论】:

  • -1,如果您阅读了异常中提供给您的非常有用的信息,您会自己解决这个问题

标签: c# .net


【解决方案1】:

你应该按照异常消息中的指示去做:

确保您的 Main 函数具有 STAThreadAttribute 标记就可以了。

[STAThread]
static void Main()
{
    // Code to run the application
}

这背后的原因是 Windows 窗体应用程序不支持从未标记为在单线程单元中运行的线程运行,如果省略此属性,应用程序将使用多线程单元模型。

更新:

如果您已经使用该属性标记了应用程序入口点并且这没有解决您的问题,那么您正在应用程序的某个地方创建线程,这些线程正在从多线程单元执行 OLE 调用。首先,您需要查明这些位置,然后根据使用场景更新您的问题,以便我们为您提供帮助。还要确保您没有从主线程以外的线程创建控件或与它们交互。

【讨论】:

  • 已经有了threadAttribute,我什至将线程的ApartmentState设置为Single。
  • 你不应该使用ApartmentState属性,因为它已经过时了,在启动相关线程之前使用SetApartmentState方法。
【解决方案2】:

打开 Program.cs 并在 void Main() 之前的行添加 [STAThread]

[STAThread]
static void Main()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    • 1970-01-01
    • 1970-01-01
    • 2012-11-29
    • 2020-08-09
    相关资源
    最近更新 更多