c# - 为什么拆分不在 UI 线程上运行的任务以使 WPF 应用程序更具响应性?

标签 c# wpf multithreading c#-4.0 task-parallel-library

part1 "Getting Started"

  • Alexandra Rusina 的系列作品。 .NET Framework 4 中的并行编程

为了使 WPF UI 响应,这是通过将密集计算外包给 UI 来完成的。最终,代码改为:

for (int i = 2; i < 20; i++)
 {
     var t = Task.Factory.StartNew(() =>
     {
         var result = SumRootN(i);
         this.Dispatcher.BeginInvoke(new Action(() =>
             textBlock1.Text += "root " + i.ToString() + " " + 
                result.ToString() + Environment.NewLine)
             ,null);
     });
 }

更新:因此将密集计算从 UI 线程中移出。

以下是来自 Part1 article 的引述来到这个片段:

  • “为了使 UI 具有响应性,我将使用任务,这是任务并行库引入的新概念。任务表示通常在单独线程上运行的异步操作”
  • “编译、运行……嗯,UI 是响应式的”

并且为了从这些单独的任务线程输出到 WPF UI(或避免 InvalidOperationException 表示“调用线程无法访问此对象,因为另一个线程拥有它。”),Dispatcher.BeginInvoke() 被使用。

同系列之二"Parallel Programming: Task Schedulers and Synchronization Context"讲述相同的代码片段(在引入局部迭代变量的小改动之后):

"This one requires more thorough refactoring. I can’t run all the tasks on the UI thread, because they perform long-running operations and this will make my UI freeze. Furthermore, it will cancel all parallelization benefits, because there is only one UI thread.

What I can do is to split each task into..."

没有the part1-articlethe part2-article矛盾?

将不在 UI 线程上运行的任务拆分成多个部分有何必要?

我在这里误解了什么?

最佳答案

我觉得这里有两个不同的概念。第 1 部分讨论在任务中运行代码以不阻塞 UI 线程。第 2 部分讨论了并行运行多个任务。一个用于“不阻塞 UI 线程”,另一个用于并行完成更多事情。如果您只有两个线程:UI 线程和任务线程,则事情不会并行发生,您也没有利用并行处理的真正威力。

关于c# - 为什么拆分不在 UI 线程上运行的任务以使 WPF 应用程序更具响应性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15762294/

相关文章:

c# - 如何使用 Linq 在字符串中搜索列表的任何项目

c# - OnActionExecuting 未在引用的 MVC 项目中执行

c# - WPF 嵌套 ListView ItemsSource

c++ - std::copy_n 中的执行策略的真正含义是什么?

c# - 在 while() 循环中使用 ManualResetEvent()

multithreading - Play Framework 中的JPA和线程

c# - 小数列,并发冲突 : the UpdateCommand affected 0 of the expected 1 records

c# - C#长数据类型拆箱问题

c# - 编辑 DataGridTextColumn 时在当前行上执行方法

wpf - 从框架内关闭 wpf 窗口