2013-12-09 20 views
0

我有多個需要在後臺運行的函數。
這些函數基本上讀取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分鐘後自動調用。 請幫我,我在哪裏做錯了?

回答

2

您的主題委託所有其工作回到UI線程(this.Dispatcher.Invoke)。只需訪問UI元素即可「調用」。

此外,從BackgroundWorker開始線程有點不同尋常。

+0

所以我應該刪除委託線程,並嘗試沒有它? –

+0

感謝隊友,它與你和Sheridan的幫助完美配合:) –

2

由於@JeffRSon已經正確地指出,你有沒有實施BackgroundWorker ...正確使用BackgroundWorker時,我們讓照顧啓動和運行Thread小號......這工作, 不是你的。這個想法是簡化Thread的使用。嘗試使用此爲您的DoWork方法來代替:

private void DoWork() 
{ 
    SaveRSSFeed(); // This is the function, and this function call other functions 
} 

請大家看看BackgroundWorker Class頁面上MSDN以獲得更多幫助與正確地執行它。