2012-12-20 173 views
2

我已經看過msdn以及有關如何使用後臺工作人員的類似堆棧交換問題。基本上,我的函數上傳程序做了實際的工作,但我想要一個線程來改變它的元素(進度條等),當我發送事件的進度改變。我試過的是以下(嚴厲編輯),它不起作用,並且在調用runworkerasync之後該程序似乎被切斷。是否有一些簡單的錯誤或將我的命令發送到另一個線程是錯誤的?另一個後臺工作人員

BackgroundWorker backgroundUpload = new System.ComponentModel.BackgroundWorker(); 

第一位是呼叫:

 if (backgroundUpload.IsBusy != true) 
     { 
      backgroundUpload.RunWorkerAsync(work); 
       // a command here for debug purposes (eg a message box) will run 
     } 
     else 
     { //it doesn't go here, this isn't the error} 

然後DoWork的,它似乎永遠不會來到這裏。

private void backgroundUpload_DoWork(object sender, DoWorkEventArgs e) 
    { 
     BackgroundWorker worker = sender as BackgroundWorker; 
     e.Result = UploadProgram((Workload)e.Argument, worker, e); //workload is one of my enums 
    } 

似乎從來沒有到過這裏。

bool UploadProgram(Workload work, BackgroundWorker worker, DoWorkEventArgs e) 
    { 
    } 

    //also there is progress changed and run worker complete. 
+1

我猜你的電話,但你必須在DoWork的事件委託的減速?即backgroundUpload.DoWork + = 新的DoWorkEventHandler(UploadProgram); –

+0

那很簡單。幹得好,每個人都有不同的感受。 –

回答

2

在代碼中缺少必要的管道,讓一個BackgroundWorker與UI溝通

你需要確保這些屬性和事件都設置正確

..... 
backgroundUpload.DoWork += backgroundUpload_DoWork 
backgroundUpload.ProgressChanged += backgroundUpload_ProgressChanged; 
backgroundUpload.WorkerReportsProgress = true; 
..... 

您需要在UI線程上運行的事件處理程序來更新進度欄

private void backgroundUpload_ProgressChanged(object sender, ProgressChangedEventArgs e) 
{ 
    progressBar.Value = (e.ProgressPercentage.ToString() + "%"); 
} 

,並在您工作時上傳文件

worker.ReportProgress(percentComplete); 
4

您是否訂閱了事件處理函數?

BackgroundWorker backgroundUpload = new System.ComponentModel.BackgroundWorker(); 
backgroundUpload.DoWork += backgroundUpload_DoWork;