我正在尝试按照函数(我在这里用数字术语写)要处理的时间来更新进度条。但它只显示最后一个被调用的值。
public static void updateProgress(int x)
{
Program.f.progressBar1.Visible = true;
Program.f.progressBar1.Enabled = true;
Program.f.progressBar1.Value +=x;
Thread.Sleep(5000);
}
public static Form1 f;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
f = new Form1();
f.progressBar1.Maximum = 100;
f.progressBar1.Minimum = 0;
f.progressBar1.Value = 0;
updateProgress(25); //fn1
updateProgress(50); //fn2
Application.Run(f);
}
progressBar直接显示75%的进度。 感谢
答案 0 :(得分:1)
错误:您在显示表单之前正在执行某些操作:
static void Main()
{
f = new Form1(); // form instance is created
f.progressBar1.Maximum = 100;
f.progressBar1.Minimum = 0;
f.progressBar1.Value = 0;
updateProgress(25); // you do something and change property
updateProgress(50); // you do something and change property
Application.Run(f); // here form is displayed and you see the most recent change
}
正确:模拟在后台运行的工作(显示表单时),您可以执行以下操作:
static void Main()
{
f = new Form1(); // form instance is created
f.progressBar1.Maximum = 100;
f.progressBar1.Minimum = 0;
f.progressBar1.Value = 0;
// create and start task running in parallel
Task.Run(() =>
{
Thread.Sleep(3000); // wait long enough until form is displayed
updateProgress(25);
updateProgress(50);
});
Application.Run(f);
}
public static void updateProgress(int x)
{
// Invoke is required because we run it in another thread
f.Invoke((MethodInvoker)(() =>
{
Program.f.progressBar1.Visible = true;
Program.f.progressBar1.Enabled = true;
Program.f.progressBar1.Value +=x;
}));
Thread.Sleep(5000); // simulate work
}