本文介绍了使用Task.Factory.StartNew时更新UI标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让我的用户界面在我的WPF应用程序的响应速度。我产生一个新的线程使用

I am trying to make my UI more responsive in my WPF app. I spawn a new thread using

Task.Factory.StartNew( () => RecurseAndDeleteStart() );

在该方法 RecurseAndDeleteStart()我想更新与被删除的文件的用户界面的标签。

In that method RecurseAndDeleteStart() I want to update a label in the UI with the file that is being deleted.

怎样才能做到这一点?

推荐答案

由于它是WPF,您可以使用调度程序并调用 Dispatcher.BeginInvoke 当元帅的回调到UI线程更新。标签

Since it's WPF, you can use the Dispatcher and call Dispatcher.BeginInvoke to marshal the call back to the UI thread to update the label.

另外,你可以传递的TaskScheduler到你的方法,并用它来更新标签如下:

Alternatively, you can pass a TaskScheduler into your method, and use it to update the label as follows:

// This line needs to happen on the UI thread...
TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();

Task.Factory.StartNew( () => RecurseAndDeleteStart(uiScheduler) );



然后,你的方法,当你想更新一个标签,你可以做内部的:

Then, inside your method, when you want to update a label, you could do:

Task.Factory.StartNew( () =>
  {
      theLabel.Text = "Foo";
  }, CancellationToken.None, TaskCreationOptions.None, uiScheduler);

这将推动回调到UI线程的同步上下文。

This will push the call back onto the UI thread's synchronization context.

这篇关于使用Task.Factory.StartNew时更新UI标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 09:07