2016-04-29 58 views
0

我想在我的應用程序的另一個線程中顯示選取框進度條。 這裏是我的代碼:使用backgroundWorker創建並顯示progressBar - VS2013

bkgWorker->RunWorkerAsync(); 

private: System::Windows::Forms::ProgressBar^ progressBar; 

private: System::Void bkgWorker_DoWork(System::Object^ sender, System::ComponentModel::DoWorkEventArgs^ e) { 
    progressBar = (gcnew System::Windows::Forms::ProgressBar()); 
    progressBar->Location = System::Drawing::Point(548, 349); 
    progressBar->MarqueeAnimationSpeed = 15; 
    progressBar->Name = L"progressBar"; 
    progressBar->Size = System::Drawing::Size(100, 23); 
    progressBar->Style = System::Windows::Forms::ProgressBarStyle::Marquee; 
    progressBar->TabIndex = 23; 
    progressBar->Show(); 
} 

private: System::Void bkgWorker_RunWorkerCompleted(System::Object^ sender, System::ComponentModel::RunWorkerCompletedEventArgs^ e) { 
    progressBar->Hide(); 
} 

沒有錯,但我沒有看到我的窗體上的進度條。 我在做什麼錯? 感謝您的幫助。

回答

0

有更好的和更新的解決方案取代了老的好背景工作者。 我建議你看看async await design. 閱讀此篇:Reporting Progress from Async Tasks

代碼應該是這個樣子:

public async void StartProcessingButton_Click(object sender, EventArgs e) 
{ 
    // The Progress<T> constructor captures our UI context, 
    // so the lambda will be run on the UI thread. 
    var progress = new Progress<int>(percent => 
    { 
    textBox1.Text = percent + "%"; 
    }); 

    // DoProcessing is run on the thread pool. 
    await Task.Run(() => DoProcessing(progress)); 
    textBox1.Text = "Done!"; 
} 

public void DoProcessing(IProgress<int> progress) 
{ 
    for (int i = 0; i != 100; ++i) 
    { 
    Thread.Sleep(100); // CPU-bound work 
    if (progress != null) 
     progress.Report(i); 
    } 
} 
相關問題