简体   繁体   English

进度条做后台工作人员 C# WinForms

[英]Progress Bar Do Work Backgroundworker C# WinForms

hope anybody can help me.希望有人能帮助我。 My problem is the progress bar in C# WinForms.我的问题是 C# WinForms 中的进度条。 I have the following Code:我有以下代码:

(There is a stupid calculate from an uint until a given number from a textbox and i want to show the progress while the calculate method is running) (从 uint 到文本框中的给定数字有一个愚蠢的计算,我想在计算方法运行时显示进度)

// The stupid method which calculate // 愚蠢的计算方法

public void ueberlaufUint()
{
    try
    {
        uint ueberlaufZahl = Convert.ToUInt32(textBox1.Text);
        do
        {
            ueberlaufZahl++;
            //Console.WriteLine(ueberlaufZahl);
        } while (ueberlaufZahl <= 100);

        label1.Text = "Endzahl: " + ueberlaufZahl;
    }
    catch (Exception)
    {
        MessageBox.Show("Only not negative natural numbers accepted");
    }
}

// Buttonclickevent // 按钮点击事件

private async void button1_Click(object sender, EventArgs e)
{
    
    ueberlaufUint();
    progressBar1.Maximum = 100;
    progressBar1.Step = 1;

    var progress = new Progress<int>(v =>
    {
        // This lambda is executed in context of UI thread,
        // so it can safely update form controls
        progressBar1.Value = v;
    });

    // Run operation in another thread
    await Task.Run(() => DoWork(progress));

    
}

// DoWork // 做工作

public void DoWork(IProgress<int> progress)
{
    // This method is executed in the context of
    // another thread (different than the main UI thread),
    // so use only thread-safe code
    for (int j = 0; j < 10000; j++)
    {
        ueberlaufUint();

        // Use progress to notify UI thread that progress has
        // changed
        if (progress != null)
            progress.Report((j + 1) * 100 / 100000);
    }
}

The progressbar only counts few steps with no dependency (in my meaning) with the calculate method.进度条仅计算与计算方法没有依赖关系的几个步骤(在我的意思中)。

Very great thanks in forward, sorry for my bad english.非常感谢转发,对不起我的英语不好。

Just a typo.只是一个错字。 You have an extra 0 in the code:您在代码中有一个额外的 0:

progress.Report((j + 1) * 100 / 100000);

should be应该

progress.Report((j + 1) * 100 / 10000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM