在对话框中显示进度

时间:2009-12-03 21:24:36

标签: c# wpf multithreading backgroundworker progress

我有一个需要很长时间的过程,我想要一个窗口来显示进度。但是,我无法想象如何显示进度。

以下是代码:

if (procced)
{
    // the wpf windows :
    myLectureFichierEnCour = new LectureFichierEnCour(_myTandemLTEclass);
    myLectureFichierEnCour.Show();

    bgw = new BackgroundWorker();
    bgw.DoWork += startThreadProcessDataFromFileAndPutInDataSet;
    bgw.RunWorkerCompleted += threadProcessDataFromFileAndPutInDataSetCompleted;

    bgw.RunWorkerAsync();
}

private void startThreadProcessDataFromFileAndPutInDataSet(object sender, DoWorkEventArgs e)
{
    _myTandemLTEclass.processDataFromFileAndPutInDataSet(
        _strCompositeKey,_strHourToSecondConversion,_strDateField);
}

我可以致电_myTandemLTEclass.processProgress以获得进展的暗示。

2 个答案:

答案 0 :(得分:6)

您应该处理ProgressChanged事件并更新用户界面中的进度条。

在执行工作的实际函数(DoWork事件处理程序)中,您将使用指定已完成任务量的参数调用ReportProgress实例的BackgroundWorker方法。

BackgroundWorker example in MSDN Library是一个简单的代码片段,可以完成这项工作。

答案 1 :(得分:1)

您的backgroundWorker线程需要处理DoWork方法和ProgressChanged

您还需要确保将WorkerReportsProgress标志设置为true(默认情况下已关闭)。

参见示例代码:

private void downloadButton_Click(object sender, EventArgs e)
{
    // Start the download operation in the background.
    this.backgroundWorker1.RunWorkerAsync();

    // Disable the button for the duration of the download.
    this.downloadButton.Enabled = false;

    // Once you have started the background thread you 
    // can exit the handler and the application will 
    // wait until the RunWorkerCompleted event is raised.

    // Or if you want to do something else in the main thread,
    // such as update a progress bar, you can do so in a loop 
    // while checking IsBusy to see if the background task is
    // still running.

    while (this.backgroundWorker1.IsBusy)
    {
        progressBar1.Increment(1);
        // Keep UI messages moving, so the form remains 
        // responsive during the asynchronous operation.
        Application.DoEvents();
    }
}