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

正如 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 回答
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 回答