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.
source share