Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

c# - Update UI Label when using Task.Factory.StartNew

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

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

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

How does one accomplish this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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);

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...