繁体   English   中英

当前线程必须在VB.NET中设置为单线程单元

[英]Current thread must be set to single thread apartment in VB.NET

这是我表单中的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文件的另一个项目中。 我该如何解决?

我使用了此站点的以下代码,它的工作原理如下:

    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;
    }

不要忽略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应用程序主线程的线程时,您将收到此异常。 这些不是用户界面组件的好客环境。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM