STAThread 方法属性和线程单元状态有什么区别?
Whats the difference between STAThread method attribute and Thread Apartment State?
我想我对什么时候需要 STAThread 有基本的了解,但是下面的方法有什么问题?
创建新线程时,设置了单元状态我没有遇到任何问题,但是当我使用 STAThread 属性装饰方法时,我收到一个异常,指出需要 STA 线程。
[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.
查看 STAThreadAttribute
页面上的 Remarks:
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.
我想我对什么时候需要 STAThread 有基本的了解,但是下面的方法有什么问题?
创建新线程时,设置了单元状态我没有遇到任何问题,但是当我使用 STAThread 属性装饰方法时,我收到一个异常,指出需要 STA 线程。
[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.
查看 STAThreadAttribute
页面上的 Remarks:
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.