2

关于如何使用后台工作人员,我查看了msdn和堆栈交换的类似问题。

基本上,我的函数上传程序完成了实际工作,但我想要一个线程来更改 ui 的元素(进度条等),并在我发送事件以更改进度时。我尝试过的如下(经过严格编辑),它不起作用,并且在调用 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}

然后做的工作,它似乎永远不会到达这里。

    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.
4

3 回答 3

4

您是否将事件处理程序订阅到该事件?

BackgroundWorker backgroundUpload = new System.ComponentModel.BackgroundWorker();
backgroundUpload.DoWork += backgroundUpload_DoWork;
于 2012-12-20T12:22:06.037 回答
4

愚蠢的问题,但你确定你订阅了这个活动吗?

backgroundUpload.DoWork += backgroundUpload_DoWork;

这是一个完整的例子,下载一个文件

于 2012-12-20T12:22:09.283 回答
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);
于 2012-12-20T12:28:03.780 回答