2011-08-09 39 views
3

我有一個涉及兩個窗體的Windows窗體應用程序。子窗體用於將數據導出到CSV文件,並使用後臺工作人員來寫入文件。在發生這種情況時,我隱藏了表單。 父表單在後臺工作程序正在運行時仍處於活動狀態,因此即使後臺工作人員正在寫入文件,用戶也可以退出應用程序。在父窗體上我添加了一個FormClosing事件處理程序來提示用戶後臺工作人員是否仍在運行。 我遇到的問題是訪問父窗體中的後臺工作人員。以下是我試過......檢查另一個窗體中的線程是否仍在運行

private void MainForm_FormClosing(object sender, FormClosingEventArgs e) 
    { 
     ExportForm eForm = new ExportForm(GridView, TableName, GridProgressBar, ProgressLabel); 

     if (eForm.PartWorker.IsBusy == true) 
      MessageBox.Show("Busy"); 
    } 

的問題將是,它是創建子窗體的新實例,因此對於它的IsBusy屬性後臺工作人員將永遠不會有真正的。我怎樣才能以父母的形式訪問這個後臺工作人員,這樣我就可以檢查這個情況是否屬實。

下面是PartWorker BackgroundWorker的代碼...

#region PartWorker Events 

    void PartWorker_DoWork(object sender, DoWorkEventArgs e) 
    { 
     GetSwitch(); 
     int batchNum = 0; 
     bool done = false; 
     ProgressLabel.Visible = true; 

     while (!done) 
     { 
      for (int i = 1; i <= 100; i++) 
      { 
       Thread.Sleep(100); 
       PartWorker.ReportProgress(i); 
      } 

      done = Export.ExportPartition(SaveFile, DataTable, 50000, batchNum++); 
     } 
    } 

    void PartWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) 
    { 
     Progress.Style = ProgressBarStyle.Blocks; 
     Progress.Value = e.ProgressPercentage; 
     //May want to put the file name that is being written here. 
     ProgressLabel.Text = "Writing File: " + e.ProgressPercentage.ToString() +"% Complete"; 
    } 

    void PartWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
    { 
     Progress.Value = 100; 
     ProgressLabel.Visible = false; 
     Progress.Visible = false; 
     MessageBox.Show("Files sucessfully created!", "Files Saved", MessageBoxButtons.OK, MessageBoxIcon.Information); 
     PartWorker.Dispose(); 
     this.Close(); 
    } 
    #endregion 

回答

3

保持在主窗體的子窗體的引用:

class MainForm : Form { 
    private ExportForm exportForm; 

    // assign exportForm wherever the child form is created 
} 

接下來,在你的ExportForm,創建一個屬性這表明表單仍然很忙。
這比訪問其BackgroundWorker(閱讀:封裝)更好。

void MainForm_FormClosing(object sender, FormClosingEventArgs e) 
{ 
    if (this.exportForm.IsBusy) 
     MessageBox.Show("Busy"); 
} 
+0

我已經實現了這一點,我可以看到它是如何工作的。但是,當我在MainForm_FormClosing事件中設置斷點時,它會轉到ExportForm中的PartWorker_ProgressChanged事件並遍歷該事件處理程序。發生這種情況時,它永遠不會執行MessageBox.Show(「Busy」)方法。 – Andrew

+0

我不太明白你在說什麼。它何時進入'ProgressChanged'處理程序?如果你不設置斷點,會發生什麼? –

+0

是的,它進入改進處理程序。如果我沒有設置斷點,MessageBox永遠不會顯示,並且您不能退出應用程序。我將發佈BackgroundWorker的事件處理程序的代碼。我很確定問題出在那裏。 – Andrew

0

創建一個單獨的業務對象持有的後臺工作,或背景的工人集合(如果你可以:

class ExportForm : Form { 
    public bool IsBusy { 
     get { return this.PartWorker.IsBusy; } 
    } 
} 

然後通過訪問新建物業辦主窗體的檢查有多個)。從子窗體創建你的後臺工作人員到這個單身人士,它將在應用程序域中的所有人都可以訪問。

相關問題