8

可能重复:
如何创建运行 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.

我需要做什么来解决这个问题?

4

3 回答 3

15

任务的想法是您可以将它们链接起来:

  var task = Task.Factory.StartNew<List<NewTwitterStatus>>(
                            () => GetTweets(securityKeys),  
                            TaskCreationOptions.LongRunning
                        )
        .ContinueWith(tsk => EndTweets(tsk) );


    void EndTweets(Task<List<string>> tsk)
    {
        var strings = tsk.Result;
        // now you have your result, Dispatchar Invoke it to the Main thread
    }
于 2012-10-29T15:21:09.473 回答
1

您需要将 Dispatcher 调用移动到看起来像这样的任务延续中:

var task = Task.Factory
    .StartNew<List<NewTwitterStatus>>(() => GetTweets(securityKeys), TaskCreationOptions.LongRunning)
    .ContinueWith<List<NewTwitterStatus>>(t =>
    {
        Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
            new Action(() =>
            {
                var result = t.Result;
                RecentTweetList.ItemsSource = result;
                Visibility = result.Any() ? Visibility.Visible : Visibility.Hidden;
            }));
    },
    CancellationToken.None,
    TaskContinuationOptions.None);
于 2012-10-29T15:21:20.813 回答
1

看起来您正在启动一个后台任务来开始阅读推文,然后在两者之间没有任何协调的情况下启动另一个任务来阅读结果。

我希望您的任务继续执行另一个任务(请参阅http://msdn.microsoft.com/en-us/library/dd537609.aspx),并且您可能需要调用回 UI 线程。 ..

var getTask = Task.Factory.StartNew(...);
var analyseTask = Task.Factory.StartNew<...>(
()=> 
Dispatcher.Invoke(RecentTweetList.ItemsSource = getTask.Result));
于 2012-10-29T15:24:02.827 回答