我应该使用哪种WPF线程方法? [英] What WPF threading approach should I go with?

查看:78
本文介绍了我应该使用哪种WPF线程方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写WPF应用程序(新技术,主要是我一直在WinForms中编写).我的目标是使UI始终保持响应性,并且我已经阅读到可以使用Threading/BackgroundWorker来实现.我认为我应该使用后台工作者来放置耗时的方法.但我计划使用方法* m_AddLog(string logText)*,该方法应将文本追加到文本框.我想从主UI线程以及后台工作人员调用此方法,因此消息将在后台处理时立即发送,而不是等待后台任务结束.您能请我建议如何正确编写这些方法以使UI完全响应,因为我对委托,调用,后台工作人员等知之甚少.

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?

推荐答案

使用任务和分派器的wpf应用程序中的大多数项目都会产生更好的结果.

Most of the items in wpf application using task and dispatcher will give better results.

看看下面的代码,希望对您有所帮助. 在下面的代码中,我考虑了从远程服务器获取图像的情况,并创建了一个用于执行此任务的任务...在for循环中,我正在使用分派的线程来更新UI来通知进度...提取所有图像的执行将被移动以继续执行块.... 您可以查看以下链接可以帮助您更好地了解它

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

这篇关于我应该使用哪种WPF线程方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆