我有一个代码可以使用以下命令从特定 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);
}
}
我现在要做的是解决无法执行其中包含的代码的问题worker_RunWorkerCompleted在一个BackgroundWorker
但每次我尝试使用BackgroundWorker
它失败并给我错误,例如:
调用线程必须是 STA,因为许多 UI 组件都需要它。
我也尝试使用STA 系统.Threading.Thread而不是BackgroundWorker,但运气不好!
我缺少什么?我对 WPF 真的很陌生,我可能忽略了一些重要的事情。
您会收到此异常,因为您的后台工作程序使用新线程,并且该线程与主 UI 线程不同。
为了简化错误消息,您无法从另一个线程更改 UI 元素,它们是独立的。
This answer会解决你的问题。
我也发现了这个answer来自@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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)