5

这是new我表单中的方法:

Public Sub New(ByVal ConnectionString As String, ByVal ConSql As SqlClient.SqlConnection, ByVal Daman As Array, ByVal SDate As Integer, ByVal FDate As Integer)

    Threading.Thread.CurrentThread.TrySetApartmentState(Threading.ApartmentState.STA)
    ' This call is required by the Windows Form Designer.
    'Error Appear in this line
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.
    Me.Sto_TypeFormFrameTableAdapter.Connection.ConnectionString = ConnectionString
    Me.Sto_typeformTableAdapter.Connection.ConnectionString = ConnectionString
    con = ConSql
    com.Connection = con
    ConNew = ConnectionString
    DamaneCod = Daman
    Start = SDate
    Final = FDate
    Fill()
End Sub

当我创建表单的新对象时,该InitializeComponent命令出错。

错误信息是:

在进行 OLE 调用之前,必须将当前线程设置为单线程单元 (STA) 模式。确保您的 Main 函数上标记了 STAThreadAttribute。

此表单在一个项目中,其输出是另一个项目的 DLL 文件,并且在使用此 DLL 文件的另一个项目中不会出现错误。我该如何解决?

4

2 回答 2

10

我已经使用了这个站点的以下代码并且它可以工作:

    using System.Threading;

    protected void Button1_Click(object sender, EventArgs e)
    {

       Thread newThread = new Thread(new ThreadStart(ThreadMethod));
       newThread.SetApartmentState(ApartmentState.STA);
       newThread.Start();     

    }

    static void ThreadMethod()
    {
       Write your code here;
    }
于 2013-02-19T06:53:40.923 回答
7

不要忽略 TrySetApartmentState() 的返回值。如果您得到 False 则没有理由尝试继续,您的代码将无法正常工作。你不妨抛出一个异常。

If Not Threading.Thread.CurrentThread.TrySetApartmentState(Threading.ApartmentState.STA) Then
    Throw New InvalidOperationException("This form is only usable from the UI thread")
End If

当您尝试从控制台模式应用程序或不是 Winforms 或 WPF 应用程序的主线程的线程中使用代码时,您将收到此异常。对于用户界面组件来说,这些环境并不好客。

需要一个线程在启动之前进入 STA单元,通过应用程序的 Main 方法上的 [STAThread] 属性或在启动线程之前调用 Thread.SetApartmentState()。并且必须调用 Application.Run() 或 Form.ShowDialog() 以获取保持表单功能所需的消息循环。通过查看调用堆栈来调试它,看看你的构造函数是如何被调用的。使用 Debug + Windows + Threads 有助于查看这是否发生在工作线程而不是应用程序的主线程上。

于 2013-01-01T15:01:17.007 回答