C# backgroundWorker和progressChanged不工作
我无法让进度条工作!如果我执行以下代码,即使代码被执行,栏仍然为空。报告进度似乎没有更新任何内容..:C# backgroundWorker和progressChanged不工作,c#,progress-bar,backgroundworker,C#,Progress Bar,Backgroundworker,我无法让进度条工作!如果我执行以下代码,即使代码被执行,栏仍然为空。报告进度似乎没有更新任何内容..: namespace GPUZ_2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); GPUZdata test = new GPUZdata { }; //invio l'oggetto
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();
}
}
}
提前感谢您的帮助我看不出您在哪里将属性设置为true-这很可能是问题所在:
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.RunWorkerAsync(test);
要初始化BackgroundWorker,必须启用进度报告并连接事件处理程序:
// Enable progress reporting
backgroundWorker1.WorkerReportsProgress = true;
// Hook up event handlers
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
我也有同样的问题。在AssemblyInfo.cs中,您应该对ComVisible进行此更改
[assembly: ComVisible(true)]
您需要做的最重要的事情:在RunWorkerCompleted事件中,永远不要忽略e.Error属性。好的,谢谢,我只是按照一个教程编写了所需的最少代码。我尝试将行添加到代码中,但没有成功,总之,我使用visual studio GUI启用了进度报告,是不是一样?谢谢!这解决了我的问题,我不明白我必须连接事件处理程序才能使它运行,谢谢:)你能提供更多的细节来证明你的答案吗。比如为什么ComVisible(true)解决了这个问题等等。。