What WPF threading approach should I go with?

时光总嘲笑我的痴心妄想 提交于 2020-02-02 11:40:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!