我已经查看了msdn以及有关如何使用后台工作者的堆栈交换的类似问题。
基本上,我的函数upload-program完成了实际的工作,但是我想要一个线程来改变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.
答案 0 :(得分:4)
您是否为活动订阅了活动处理程序?
BackgroundWorker backgroundUpload = new System.ComponentModel.BackgroundWorker();
backgroundUpload.DoWork += backgroundUpload_DoWork;
答案 1 :(得分:4)
愚蠢的问题,但你确定你订阅了这个活动吗?
backgroundUpload.DoWork += backgroundUpload_DoWork;
答案 2 :(得分: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);