The current thread must be installed in a single-threaded apartment in VB.NET

This is the new method in my form:

 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 

When I create a new object of my form, the InitializeComponent command gets an error.

Error message:

The current stream must be set to single-threaded apartment (STA) before OLE calls. Make sure your main function is STAThreadAttribute marked on it.

This form is in a project whose output is a DLL file for another project, and the error does not appear in another project that used this DLL file. How can i fix this?

+4
source share
2 answers

I used the following code for this site and it works:

  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; } 
+8
source

Do not ignore the return value of TrySetApartmentState (). If you get False, then there is no reason to continue, your code will not work. You can also throw an exception.

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

You will get this exception when trying to use your code from a console mode application or from a thread that is not the main thread of a Winforms or WPF application. This is not a welcoming environment for a user interface component.

It requires a thread that entered the STA apartment before it started, either using the [STAThread] attribute of the main application method, or by calling Thread.SetApartmentState () before starting the thread. And Application.Run () or Form.ShowDialog () must be called to get the required message loop that keeps the form functional. Debug this by looking at the call stack to find out how your constructor is called. Using Debug + Windows + Threads is useful to find out if this happened in the workflow instead of the main application thread.

+7
source

All Articles