我有一个简单的Backgroundworker,想把我的结果写到控制台,我也想报告这个过程。
class Program
{
private static BackgroundWorker worker;
static int counter;
static void Main(string[] args)
{
worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.RunWorkerAsync();
Console.ReadLine();
}
static void worker_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
counter++;
worker.ReportProgress(counter);
}
}
static void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine(counter);
}
static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
}
但是如何将我的String(或多于1个字符串)提供给我的ReportProcess函数?
答案 0 :(得分:1)
您没有将事件处理程序分配给BackgroundWorker
事件:
static void Main(string[] args)
{
worker = new BackgroundWorker();
worker.DoWork += Worker_DoWork; //here
worker.ProgressChanged += Worker_ProgressChanged; //and here
worker.WorkerReportsProgress = true;
worker.RunWorkerAsync();
Console.ReadLine();
}
干杯
答案 1 :(得分:0)
您将计数器作为第一个(int percentProgress)参数传递给ReportProgress,您可以使用e.ProgressPercentage访问该示例,如下例所示。您还可以传递第二个(对象userState)参数,该参数可以是字符串或任何其他对象,使用e.UserState访问,如下例所示。
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
backgroundWorker.ReportProgress(100, "Complete!");
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
toolStripProgressBar.Value = e.ProgressPercentage;
toolStripStatusLabel.Text = e.UserState as String;
}
请参阅https://msdn.microsoft.com/en-us/library/system.windows.forms.toolstripprogressbar(v=vs.110).aspx
上的完整示例