任务结果上的事件已完成

Dev*_*per 8 .net c# wpf task-parallel-library

可能重复:
如何创建运行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;
    }));
Run Code Online (Sandbox Code Playgroud)

我收到了错误:

var result = task.Result; // ERROR!!! The calling thread cannot access this object because a different thread owns it.
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能解决这个问题?

Hen*_*man 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
    }
Run Code Online (Sandbox Code Playgroud)