2

Parallel.For 内から WPF テキストブロックを更新しようとしていますが、できません。私はディスパッチャーを使用していますが、間違った方法で行っていると思います。最初にすべての作業が完了し、次にテキストブロックが反復的かつ高速に更新されます。これが私のコードです:

Parallel.For(0, currentScene.Textures.Count, delegate(int i)
       {

           TextureObject texture = (currentScene.Textures[i]);

           MainWindow.Instance.StatusBarText.Dispatcher.BeginInvoke(new Action(()
               => MainWindow.Instance.StatusBarText.Text = "Loading Texture " + i
               + " - " + texture.Name ), null);
           LoadTexture(texture);
           }
       });
4

3 に答える 3

1

Parallel.For 呼び出し自体が UI スレッドで行われ、呼び出しが戻るまでそのスレッドの更新がブロックされます。代わりにこれを行います:

    Task.Create(delegate   
    {   
       Parallel.For( /* your current code */ );
    });   

ただし、BackgroundWorker クラスは、このシナリオのより適切なソリューションである可能性があります...

参照: http://social.msdn.microsoft.com/Forums/en/parallelextensions/thread/38d7a436-e1d1-4af8-8525-791ebeed9663

于 2011-01-30T03:11:25.533 に答える
0

ロバートの言うとおりですが、私ならこう書きます。

Enumerable.Range(0, currentScene.Textures.Count).Select(i =>
    new Task(() => {
       TextureObject texture = (currentScene.Textures[i]);

       MainWindow.Instance.Dispatcher.BeginInvoke(new Action(()
           => MainWindow.Instance.StatusBarText.Text = "Loading Texture " + i
           + " - " + texture.Name ), null);
       LoadTexture(texture);
    });
).Run(x => x.Start());

座って他のタスクを待つだけのタスクを作成する必要はありません。

于 2011-01-30T03:47:15.653 に答える
0

Levy 氏が指摘しているように、Parallel.For() への呼び出しは、すべてのループ反復が完了するまでブロッキング呼び出しになります。そのため、上記で提案したことを行うか、単にバックグラウンド スレッドで呼び出しをラップすることができます。

ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object arg)
{
    Parallel.For(0, currentScene.Textures.Count, delegate(int i)        
    {
        // The rest of your code .....
    }
}));
于 2011-01-31T03:41:52.557 に答える