Skip to main content
 首页 » 编程设计

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

2024年02月13日9落叶无声

在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-article与the part2-article矛盾?

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

我在这里误解了什么?

请您参考如下方法:

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