C#/ WPF – 我无法从后台工作者更新UI

我有一个代码,使用Tweetsharp库从特定的Twitter帐户获取推文,创建自定义UserControl实例,并将推文文本发布到该UserControl然后将其添加到StackPanel

但是,我必须得到很多推文,似乎应用程序会在向StackPanel添加用户控件时冻结。 我尝试过使用BackgroundWorker ,但直到现在我还不幸运。

我的代码:

 private readonly BackgroundWorker worker = new BackgroundWorker(); // This ( UserControl ) is used in the MainWindow.xaml private void UserControl_Loaded_1(object sender, RoutedEventArgs e) { worker.DoWork += worker_DoWork; worker.RunWorkerCompleted += worker_RunWorkerCompleted; worker.RunWorkerAsync(); } private void worker_DoWork(object sender, DoWorkEventArgs e) { int usrID; var service = new TwitterService(ConsumerKey, ConsumerSecret); service.AuthenticateWith(AccessToken, AccessTokenSecret); ListTweetsOnUserTimelineOptions options = new ListTweetsOnUserTimelineOptions(); options.UserId = usrID; options.IncludeRts = true; options.Count = 10; twitterStatuses = service.ListTweetsOnUserTimeline(options); } private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { try { foreach (var item in twitterStatuses) { TweetViewer tweetViewer = new TweetViewer(); // A UserControl within another UserControl tweetViewer.Tweet = item.Text; tweetViewer.Username = "@stackoverflow"; tweetViewer.RealName = "Stack Overflow" tweetViewer.Avatar = ImageSourcer(item.Author.ProfileImageUrl); stackPanel.Children.Add(tweetViewer); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } 

我现在想要做的是解决无法在BackgroundWorker执行worker_RunWorkerCompleted中包含的代码的问题,但每次我尝试使用BackgroundWorker执行它时它都会失败并给出如下错误:

调用线程必须是STA,因为许多UI组件都需要这个。

我也试过使用STA System.Threading.Thread而不是BackgroundWorker但没有运气!

我错过了什么? 我是WPF的新手,我可能会忽略一些重要的东西。

您得到此exception,因为您的后台工作程序使用新线程,并且此线程与主UI线程不同。 为简化错误消息说您无法从另一个线程更改UI元素,它们是独立的。

这个答案将解决您的问题。

我也从@Marc Gravell找到了这个答案

 ///...blah blah updating files string newText = "abc"; // running on worker thread this.Invoke((MethodInvoker)delegate { someLabel.Text = newText; // runs on UI thread }); ///...blah blah more updating files