调用线程必须是STA,因为许多UI组件需要这样做 [英] The calling thread must be STA, because many UI components require this
问题描述
我正在使用 http://www.codeproject .com / KB / IP / Facebook_API.aspx
我试图调用 WPF 创建的wiki / Extensible_Application_Markup_Languagerel =noreferrer> XAML 。但是它给我一个错误:
调用线程必须是STA,因为许多UI组件需要这个。
我不知道该怎么办我试图这样做:
FacebookApplication.FacebookFriendsList ffl = new FacebookFriendsList();
但它是给我的错误。
我添加了一个后台工作者:
static BackgroundWorker bw = new BackgroundWorker();
static void Main(string [] args)
{
bw.DoWork + = bw_DoWork;
bw.RunWorkerAsync(Message to worker);
Console.ReadLine();
}
static void bw_DoWork(object sender,DoWorkEventArgs e)
{
//这是在工作线程上调用
FacebookApplication.FacebookFriendsList ffl =新的FacebookFriendsList();
Console.WriteLine(e.Argument); //将Message to worker写入
//执行耗时的任务...
}
如果从主线程进行调用,则必须将STAThread属性添加到Main方法中,如上一个答案所述。 p>
如果您使用单独的线程,则需要在STA(单线程公寓)中,后台工作线程不是这样。您必须自己创建线程,如下所示:
Thread t = new Thread(ThreadProc) ;
t.SetApartmentState(ApartmentState.STA);
t.Start();
ThreadProc是ThreadStart类型的代理。
I am using http://www.codeproject.com/KB/IP/Facebook_API.aspx
I am trying to call the XAML which is created using WPF. But it gives me an error:
The calling thread must be STA, because many UI components require this.
I don't know what to do. I am trying to do this:
FacebookApplication.FacebookFriendsList ffl = new FacebookFriendsList();
But it is giving me that error.
I added a background worker:
static BackgroundWorker bw = new BackgroundWorker();
static void Main(string[] args)
{
bw.DoWork += bw_DoWork;
bw.RunWorkerAsync("Message to worker");
Console.ReadLine();
}
static void bw_DoWork(object sender, DoWorkEventArgs e)
{
// This is called on the worker thread
FacebookApplication.FacebookFriendsList ffl = new FacebookFriendsList();
Console.WriteLine(e.Argument); // Writes "Message to worker"
// Perform time-consuming task...
}
If you make the call from the main thread, you must add the STAThread attribute to the Main method, as stated in the previous answer.
If you use a separate thread, it needs to be in a STA (single-threaded apartment), which is not the case for background worker threads. You have to create the thread yourself, like this:
Thread t = new Thread(ThreadProc);
t.SetApartmentState(ApartmentState.STA);
t.Start();
with ThreadProc being a delegate of type ThreadStart.
这篇关于调用线程必须是STA,因为许多UI组件需要这样做的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!