后台工作者不会报告进度
Background Worker won't report progress
我有一个不报告进度的 Backrgound Worker。我需要得到一个确切的值,而不是百分比。我不确定如何编写进度更改事件的代码。我已将 WorkReportsProgress 属性 设置为 true。我对 C# 还是比较陌生,所以请原谅我的知识不足。
private void BKGWork_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; i <= 20; i++)
{
//do work
worker.ReportProgress(i);
}
}
private void BKGWork_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//not sure how to get the exact value of i and compare it to see which loop the background worker is in.
}
使用worker.ReportProgress(0,i);
将您的显式值作为用户状态参数传递。 Use can access this in e.UserState
将其转换为 int
无论您作为第一个参数传递给 ReportProgress
的是您在 e.ProgressPercentage
中收到的值,BackgroundWorker class 都无法为您计算 'Percentage'。如果您需要更复杂的数据(例如 class 的实例,您可以使用 ReportProgress 的第二个可选参数并在 UserState 参数
中检索它
private void BKGWork_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; i <= 20; i++)
{
//do work
worker.ReportProgress(i);
}
}
private void BKGWork_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// This is the value of the variable i passed above
Console.WriteLine(e.ProgressPercentage);
}
根据您在下方的评论,您似乎没有正确设置事件处理程序。如果您可以使用调试器,这很容易发现。在 ProgressChanged 事件和 运行 程序 (F5) 内的行中放置一个断点 (F9)。如果未命中断点,则检查您是否已在设计器或代码中正确设置事件处理程序。否则,如果遇到断点,则查看 Visual Studio 的输出 window(在 运行 时,在非控制台应用程序中,控制台输出被重定向到输出 window Visual Studio)
我有一个不报告进度的 Backrgound Worker。我需要得到一个确切的值,而不是百分比。我不确定如何编写进度更改事件的代码。我已将 WorkReportsProgress 属性 设置为 true。我对 C# 还是比较陌生,所以请原谅我的知识不足。
private void BKGWork_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; i <= 20; i++)
{
//do work
worker.ReportProgress(i);
}
}
private void BKGWork_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//not sure how to get the exact value of i and compare it to see which loop the background worker is in.
}
使用worker.ReportProgress(0,i);
将您的显式值作为用户状态参数传递。 Use can access this in e.UserState
将其转换为 int
无论您作为第一个参数传递给 ReportProgress
的是您在 e.ProgressPercentage
中收到的值,BackgroundWorker class 都无法为您计算 'Percentage'。如果您需要更复杂的数据(例如 class 的实例,您可以使用 ReportProgress 的第二个可选参数并在 UserState 参数
private void BKGWork_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; i <= 20; i++)
{
//do work
worker.ReportProgress(i);
}
}
private void BKGWork_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// This is the value of the variable i passed above
Console.WriteLine(e.ProgressPercentage);
}
根据您在下方的评论,您似乎没有正确设置事件处理程序。如果您可以使用调试器,这很容易发现。在 ProgressChanged 事件和 运行 程序 (F5) 内的行中放置一个断点 (F9)。如果未命中断点,则检查您是否已在设计器或代码中正确设置事件处理程序。否则,如果遇到断点,则查看 Visual Studio 的输出 window(在 运行 时,在非控制台应用程序中,控制台输出被重定向到输出 window Visual Studio)