我正在使用以下代码:
我正在遇到一个错误:
我需要怎么做才能解决这个问题?
可能是重复问题:
如何创建运行STA线程的任务(TPL)?
我正在使用以下代码:
var task = Task.Factory.StartNew<List<NewTwitterStatus>>(
() => GetTweets(securityKeys),
TaskCreationOptions.LongRunning);
Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action(() =>
{
var result = task.Result; // ERROR!!! The calling thread cannot access this object because a different thread owns it.
RecentTweetList.ItemsSource = result;
Visibility = result.Any() ? Visibility.Visible : Visibility.Hidden;
}));
我正在遇到一个错误:
var result = task.Result; // ERROR!!! The calling thread cannot access this object because a different thread owns it.
我需要怎么做才能解决这个问题?
Task.Result
会阻塞直到结果可用,因此如果此代码没有出错,则在等待任务完成时会阻塞UI线程;那将是不好的。您需要等待实际获得结果后再调用UI线程。 - Servy