I think I do have a basic understanding of when STAThread is required, but what is problematic in the approach below?
When a new thread is created the Apartment State is set I don't get any issues but when I decorate the method with the STAThread attribute I get an exception stating that an STA thread is required.
[STAThread]
public void DoSomething()
{
//Does something
}
VS
public void DoSomething()
{
Thread thread = new Thread(new ThreadStart(() => //Does Something );
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
System.Windows.Markup.XamlParseException HResult=0x80131501
Message='The invocation of the constructor on type 'System.Windows.Controls.UserControl' that matches the specified binding constraints threw an exception.' Line number '4' and line position '6'.> Inner Exception 1: InvalidOperationException: The calling thread must be STA, because many UI components require this.
See the Remarks on the STAThread​Attribute
page:
Apply this attribute to the entry point method (the
Main()
method in C# and Visual Basic). It has no effect on other methods. To set the apartment state of threads you start in your code, use the Thread.SetApartmentState or Thread.TrySetApartmentState method before starting the thread.
User contributions licensed under CC BY-SA 3.0