progressBar 只更新最后调用的值

progressBar only updating last called value

我正在尝试根据函数所花费的时间(我在此处以数字形式写的)将进度条更新为 processed.But 它仅显示最后调用的值。

public static void updateProgress(int x)
    {
        Program.f.progressBar1.Visible = true;
        Program.f.progressBar1.Enabled = true;
        Program.f.progressBar1.Value +=x;
        Thread.Sleep(5000);
    }

上面的fn是用来更新进度条的。

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%的进度。 谢谢

错误:您在表单显示之前正在做一些事情:

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
}