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

ツイートの読み取りを開始するバックグラウンド タスクを開始し、2 つの間の調整なしで結果を読み取る別のタスクを開始しているようです。

あなたのタスクには継続に別のタスクがあると予想されます(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 に答える
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 に答える