2012-03-10 184 views
2

我無法獲得進度條的工作!如果即使代碼被執行ReportProgress犯規我執行下面的代碼吧保留爲空似乎任何更新..:backgroundWorker和progressChanged不工作

namespace GPUZ_2 

{ 
public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 

     GPUZdata test = new GPUZdata 
     { 
     }; 

     //invio l'oggetto al thread backgroundworker 
     backgroundWorker1.RunWorkerAsync(test); 
    } 


    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
    { 
     // 
     // e.Argument always contains whatever was sent to the background worker 
     // in RunWorkerAsync. We can simply cast it to its original type. 
     // 
     GPUZdata argumentTest = e.Argument as GPUZdata; 




     argumentTest.OneValue = 6; 
     Thread.Sleep(2000); 
     backgroundWorker1.ReportProgress(50); 
     argumentTest.TwoValue = 3; 
     Thread.Sleep(2000); 
     backgroundWorker1.ReportProgress(100); 


     // 
     // Now, return the values we generated in this method. 
     // Always use e.Result. 
     // 
     e.Result = argumentTest; 
    } 


    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
    { 

     // Receive the result from DoWork, and display it. 

     GPUZdata test = e.Result as GPUZdata; 
     this.Text = test.OneValue.ToString() + " " + test.TwoValue.ToString(); 

    } 

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) 
    { 
     // Change the value of the ProgressBar to the BackgroundWorker progress. 
     progressBar1.Value = e.ProgressPercentage; 
     // Set the text. 
     this.Text = e.ProgressPercentage.ToString(); 
    } 
} 

}

在此先感謝您的幫助

+2

最重要的事:在RunWorkerCompleted事件*從未*忽略e.Error財產。 – 2012-03-10 23:06:14

+0

好的,謝謝,我只是跟着一個教程,需要最少的代碼 – rekotc 2012-03-11 13:01:51

回答

5

要初始化BackgroundWorker的,您必須啓用進度報告並掛上你的事件處理程序:

// Enable progress reporting 
backgroundWorker1.WorkerReportsProgress = true; 

// Hook up event handlers 
backgroundWorker1.DoWork += backgroundWorker1_DoWork; 
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted; 
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged; 
+0

謝謝!這解決了我的問題,我不明白,我不得不掛接事件處理程序,以使其運行,謝謝:) – rekotc 2012-03-11 13:04:15

3

我不「看不到你設置WorkerReportsProgress屬性爲true - 最有可能的問題是:

backgroundWorker1.WorkerReportsProgress = true; 
backgroundWorker1.RunWorkerAsync(test); 
+0

我試圖添加行到代碼,但沒有運氣,無論如何,我使用Visual Studio GUI啓用進度報告,是不是一樣? – rekotc 2012-03-11 13:02:56

-1

我有同樣的問題。在AssemblyInfo.cs中,您應該對ComVisible進行此更改。你需要

[assembly: ComVisible(true)] 
+0

你能提供更多的細節來證明你的答案。就像爲什麼ComVisible(true)解決了問題等。 – 2016-12-16 11:23:45

相關問題