【发布时间】:2012-10-29 15:09:22
【问题描述】:
我正在使用以下代码:
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 线程,直到实际得到结果。
标签: c# .net wpf task-parallel-library