在后台C#WPF中运行多个函数
我有多个功能需要在后台运行。在后台C#WPF中运行多个函数,c#,wpf,C#,Wpf,我有多个功能需要在后台运行。 这些函数基本上读取RSS XML提要并将提要数据保存到在线数据库中,问题是在执行这些函数时整个应用程序都会被卡住。 我所希望的是,它不应该被卡住,整个应用程序应该以正常的方式运行。 我尝试了后台工作程序(可能是我以错误的方式实现了它) 以下是代码: BackgroundWorker bw; public HomePage() { InitializeComponent(); bw = new Background
这些函数基本上读取RSS XML提要并将提要数据保存到在线数据库中,问题是在执行这些函数时整个应用程序都会被卡住。
我所希望的是,它不应该被卡住,整个应用程序应该以正常的方式运行。
我尝试了后台工作程序(可能是我以错误的方式实现了它)
以下是代码:
BackgroundWorker bw;
public HomePage()
{
InitializeComponent();
bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += bw_DoWork;
DispatcherTimer d = new System.Windows.Threading.DispatcherTimer();
d.Tick += new EventHandler(dispatcherTimer_Tick);
d.Interval = new TimeSpan(0, 15, 0);
d.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
if (!this.bw.IsBusy)
{
bw.RunWorkerAsync();
}
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
DoWork();
}
void DoWork()
{
try
{
System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(
delegate()
{
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(
delegate()
{
SaveRSSFeed(); // This is the function, and this function call other functions
}
));
}
));
thread.IsBackground = true;
thread.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
注意:这些函数在15分钟后自动调用。
请帮帮我,我哪里做错了?您的线程将所有的工作委托回UI线程(
this.Dispatcher.Invoke
)。只需要“调用”对UI元素的访问
此外,从
BackgroundWorker
启动线程是有点不寻常的,您的线程将其所有工作委托回UI线程(this.Dispatcher.Invoke
)。只需要“调用”对UI元素的访问
此外,从
BackgroundWorker
启动线程有点不寻常,正如@jefferson正确指出的那样,您没有正确地实现BackgroundWorker
。。。当使用BackgroundWorker
时,我们让它负责启动和运行线程
s。。。那是你的工作,不是你的。其思想是简化线程
s的使用。尝试将此作为您的DoWork
方法:
private void DoWork()
{
SaveRSSFeed(); // This is the function, and this function call other functions
}
请查看MSDN上的页面,以获得有关正确实施它的更多帮助。正如@Jefferson正确指出的,您尚未正确实施您的
BackgroundWorker
。。。当使用BackgroundWorker
时,我们让它负责启动和运行线程
s。。。那是你的工作,不是你的。其思想是简化线程
s的使用。尝试将此作为您的DoWork
方法:
private void DoWork()
{
SaveRSSFeed(); // This is the function, and this function call other functions
}
有关正确实施MSDN的更多帮助,请查看MSDN页面。谢谢mate,它与您和Sheridan的帮助完美配合:)谢谢mate,它与您和Sheridan的帮助完美配合:)