我创建了一个运行大约需要 5 分钟的控制台应用程序。main 方法调用了大约 10 个完成工作的方法。
如何通过这 10 种方法将 Console App 更改为更新进度条/显示最新进度的 Windows Forms 应用程序?
非常感谢!
我创建了一个运行大约需要 5 分钟的控制台应用程序。main 方法调用了大约 10 个完成工作的方法。
如何通过这 10 种方法将 Console App 更改为更新进度条/显示最新进度的 Windows Forms 应用程序?
非常感谢!
您可以BackgroundWorker
在 Winforms 中使用组件。只需复制粘贴此代码。我用过一个Label instead of ProgressBar
. percentage completion
随着任务在后台进行,标签会更新。
耗时的方法/任务必须在Do_Work
处理程序中调用。运行下面的示例。
using System.ComponentModel;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form3 : Form
{
private BackgroundWorker _worker;
BusinessClass _biz = new BusinessClass();
public Form3()
{
InitializeComponent();
InitWorker();
}
private void InitWorker()
{
if (_worker != null)
{
_worker.Dispose();
}
_worker = new BackgroundWorker
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};
_worker.DoWork += DoWork;
_worker.RunWorkerCompleted += RunWorkerCompleted;
_worker.ProgressChanged += ProgressChanged;
_worker.RunWorkerAsync();
}
/// Do the time consuming work here
void DoWork(object sender, DoWorkEventArgs e)
{
int highestPercentageReached = 0;
if (_worker.CancellationPending)
{
e.Cancel = true;
}
else
{
double i = 0.0d;
int junk = 0;
for (i = 0; i <= 199990000; i++)
{
int result = _biz.MyFunction(junk);
junk++;
// Report progress as a percentage of the total task.
var percentComplete = (int)(i / 199990000 * 100);
if (percentComplete > highestPercentageReached)
{
highestPercentageReached = percentComplete;
// note I can pass the business class result also and display the same in the LABEL
_worker.ReportProgress(percentComplete, result);
_worker.CancelAsync();
}
}
}
}
void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
// Display some message to the user that task has been
// cancelled
}
else if (e.Error != null)
{
// Do something with the error
}
}
void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label1.Text = string.Format("Result {0}: Percent {1}",e.UserState, e.ProgressPercentage);
}
}
public class BusinessClass
{
public int MyFunction(int input)
{
return input+10;
}
}
}