2009-06-09 41 views
3

我有下面的代碼中提取數據:C#.NET - 如何取消一個BackgroundWorker從一個WebService

void ReferenceManager_DoWork(object sender, DoWorkEventArgs e) 
{ 
    try 
    { 

     // Get the raw data 
     byte[] data = this.GetData(IvdSession.Instance.Company.Description, IvdSession.Instance.Company.Password); 

     // Deserialize the list 
     List<T> deseriaizedList = null; 
     using (MemoryStream ms = new MemoryStream(data)) 
     { 
      deseriaizedList = Serializer.Deserialize<List<T>>(ms); 
     } 

     // Convert the list to the Reference Interface 
     List<IReference> referenceList = new List<IReference>(); 
     foreach (T entity in deseriaizedList) 
     { 
      IReference reference = (IReference)entity; 
      referenceList.Add(reference); 
     } 

     e.Result = referenceList; 

    } 
    catch (WebException) 
    { 
     e.Result = null; 
    } 
} 

的代碼基本上是調用委託給一個WebService方法。不幸的是,我使用後臺工作的主要原因是在加載數據時停止UI凍結。我有一個表單彈出,請稍候,點擊此處取消。

在取消點擊我後臺工作者調用CancelAsync。現在,因爲我沒有循環,所以我看不到漂亮的檢查取消的方法。我能看到的唯一的選擇是有...

byte[] m_CurrentData; 

...調用WebService的填充m_CurrentData方法外和的DoWork(..)開始啓動一個新的線程。然後我需要執行循環檢查,如果取消或檢查m_CurrentData是否不再爲空。

有沒有更好的取消方法?

回答

3

實際的工作似乎在this.GetData(...)方法內完成,未顯示。我收集它正在調用一個web服務。您可能應該調用代理對象上的Abort()方法來阻止客戶端等待響應。撥打CancelAsync()毫無意義,只要確保在RunWorkerCompleted()中正確檢查錯誤即可。最簡單的方法可能是而不是來捕獲_DoWork()中的任何異常,但請檢查Completed()中的Result.Error屬性。無論如何,你應該這樣做。

爲了澄清,CancelAsync()方法僅用於在DoWork()內停止循環。你沒有在那裏運行(有意義的)循環,所以需要另一種方法。

1

更新

我剛剛檢查了MSDN for DoWorkEventArgs並意識到我以前的答案是錯的。 BackgroundWorker上的CancellationPending屬性由CancelAsyncfrom the MSDN)調用設置。因此你的DoWork方法可以變成:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
{ 
    // Do not access the form's BackgroundWorker reference directly. 
    // Instead, use the reference provided by the sender parameter. 
    BackgroundWorker bw = sender as BackgroundWorker; 

    // Extract the argument. 
    int arg = (int)e.Argument; 

    // Start the time-consuming operation. 
    e.Result = TimeConsumingOperation(bw, arg); 

    // If the operation was canceled by the user, 
    // set the DoWorkEventArgs.Cancel property to true. 
    if (bw.CancellationPending) 
    { 
     e.Cancel = true; 
    } 
} 

你能用這個嗎?

+0

嗨,DoWork有e.Cancel提供取消通知。我的方法不會循環,因此無法檢查e.Cancel是否已更改爲true。 – GenericTypeTea 2009-06-09 19:36:43

+0

啊 - 我讀過,但顯然沒有完全接受,你的問題的一部分。我會看看我能否更新答案。 – ChrisF 2009-06-09 19:40:09

相關問題