我有多個需要在後臺運行的函數。
這些函數基本上讀取RSS XML提要並將提要數據保存到在線數據庫,問題是當這些函數正在執行時,整個應用程序會卡住。
所有我想要它不應該卡住,整個應用程序應該表現正常的方式。
我試過後臺工作(可能我在錯誤的方式來實現它)
這裏是代碼:在後臺運行多個函數C#WPF
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分鐘後自動調用。 請幫我,我在哪裏做錯了?
所以我應該刪除委託線程,並嘗試沒有它? –
感謝隊友,它與你和Sheridan的幫助完美配合:) –