问题
I'm writing a WPF application (new technique, mostly I've been writing in WinForms). My goal is to make UI responsive whole time, and I've read that it can be achived using Threading/BackgroundWorker. I think that I should use background worker to put there time consuming methods. But I plan to use method *m_AddLog(string logText)* which should append text to textbox. This method I want to call from main UI thread aswell as from background worker, so messages would be sent immediatelly while processing in backround instead of waiting for background task to end. Could you please kindly advise how to write properly write these methods for UI being fully responsive as I don't know much about delegates, invoking, background workers, etc?
回答1:
Most of the items in wpf application using task and dispatcher will give better results.
have a Look at the following code hope this may helps you.. In the below code i have considered a scenario like fetching images from remote server and i created a task for doing that... in the task in side for loop i am using dispatched thread to update UI to notify the progress... and after fetching all the images execution will be moved to continue block.... You can have a look at the following link that may helps you to understand it better
ObservableCollection items= new ObservableCollection();
TaskFactory tFactory = new TaskFactory();
tFactory.StartNew(() =>
{
for (int i = 0; i < 50; i++)
{
//Request to server
System.Windows.Application.Current.Dispatcher.BeginInvoke((Action)delegate()
{
// UPDATE PROGRESS BAR IN UI
});
items.Add(("");
}
}).ContinueWith(t =>
{
if (t.IsFaulted)
{
// EXCEPTION IF THREAD IS FAULT
throw t.Exception;
}
System.Windows.Application.Current.Dispatcher.BeginInvoke((Action)delegate()
{
//PROCESS DATA AND DISPLAY
});
});
回答2:
If you want to run some background process then update the UI on completion the following pattern works well (if ran from the UI thread).
Task.Factory.StartNew(() =>
{
// Background work
}).ContinueWith((t) => {
// Update UI thread
}, TaskScheduler.FromCurrentSynchronizationContext());
Put the background work in the first task and the UI work in the following his is task. The TaskScheduler option ensures the second task runs on the UI thread.
回答3:
As People Said there are tons of question that will show you how to do that But if you want to compare it you can find it here with detailed comparison
来源:https://stackoverflow.com/questions/7582853/what-wpf-threading-approach-should-i-go-with