2010-04-29 65 views

回答

0

爲了不鎖定在UI線程開始在另一個線程的數據讀取。你可以在UI上公開一個方法(假設你在這裏分離圖層)並從業務層調用該方法。 Windows窗體控件公開一個InvokeRequired標誌,您可以使用該標誌來檢查是否從正確的線程調用控件。如果你沒有在正確的線程上,你可以打電話給一個委託來做。

/// <summary> 
    /// Delegate to notify UI thread of worker thread progress. 
    /// </summary> 
    /// <param name="total">The total to be downloaded.</param> 
    /// <param name="downloaded">The amount already downloaded.</param> 
    public delegate void UpdateProgressDelegate(int total, int downloaded); 

    /// <summary> 
    /// Updates the progress in a thread-safe manner. 
    /// </summary> 
    /// <param name="total">The total.</param> 
    /// <param name="downloaded">The downloaded.</param> 
    public void UpdateProgress(int total, int downloaded) 
    { 
     // Check we are on the right thread. 
     if (!this.InvokeRequired) 
     { 
      this.ProgressBar.Maximum = total; 
      this.ProgressBar.Value = downloaded; 
     } 
     else 
     { 
      if (this != null) 
      { 
       UpdateProgressDelegate updateProgress = new UpdateProgressDelegate(this.UpdateProgress); 

       // Executes a delegate on the thread that owns the control's underlying window handle. 
       this.Invoke(updateProgress, new object[] { total, downloaded }); 
      } 
     } 
    } 

或者你可以只使用一個BackgroundWoker;)

相關問題