并行。用于更新文本块
我正在尝试从 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);
}
});
I am trying to update a WPF textblock from within a Parallel.For and I can't. I use a dispatcher but I guess, I do it the wrong way. All of the work is done at first and then the textblock updates iteratively and fast. Here's my code:
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);
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Parallel.For 调用本身是在您的 UI 线程上进行的,阻止该线程更新,直到调用返回。相反,请执行此操作:
BackgroundWorker 类可能是这种情况下更合适的解决方案...
参考:http://social.msdn.microsoft.com/Forums/en/parallelextensions/thread/38d7a436-e1d1-4af8-8525-791ebeed9663
The Parallel.For call is itself being made on your UI thread, blocking that thread from updating until the call returns. Do this instead:
The BackgroundWorker class may be a more appropriate solution for this scenario though...
Reference: http://social.msdn.microsoft.com/Forums/en/parallelextensions/thread/38d7a436-e1d1-4af8-8525-791ebeed9663
罗伯特是对的,但我会这样写:
不需要创建一个其唯一工作就是等待其他任务的任务。
Robert's right, but here's how I would write it:
No need to create a Task whose sole job is to sit and wait on other Tasks.
正如 Levy 先生指出的那样,对 Parallel.For() 的任何调用都将是阻塞调用,直到所有循环迭代完成为止。因此,您可以执行上面建议的操作,或者简单地将调用包装在后台线程中。
As Mr. Levy points out any call to Parallel.For() will be a blocking call until all the loop iterations have completed. As such, you can do what was suggested above or simply wrap the invocation in a background thread.