【问题标题】:Progress Bar Do Work Backgroundworker C# WinForms进度条在后台工作 C# WinForms
【发布时间】:2020-10-26 19:24:20
【问题描述】:

希望有人可以帮助我。我的问题是 C# WinForms 中的进度条。我有以下代码:

(从 uint 到文本框中的给定数字有一个愚蠢的计算,我想在计算方法运行时显示进度)

// 愚蠢的计算方法

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");
    }
}

// 按钮点击事件

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));

    
}

// 做工

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);
    }
}

进度条只计算几个步骤,与计算方法没有依赖关系(在我的意思中)。

非常感谢转发,抱歉我的英语不好。

【问题讨论】:

  • 这里没有 BackGroundWorker。 -- 您不能在ueberlaufUint() 方法中访问控件。如果您需要textBox1.Text 的值,请预先将其转换并传递给DoWork() 方法。您可以在 IProgress 处理程序中访问控件。
  • 感谢您的快速响应...这是什么意思?我需要一个 Backgroundworker 并在那里输入我的方法吗?

标签: c# winforms methods backgroundworker progress


【解决方案1】:

只是一个错字。您的代码中有一个额外的 0:

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

应该是

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

【讨论】:

  • 谢谢 Mike67 :) 这解决了我的进度条填充完成的问题.. 但是函数和进度条之间是否存在依赖关系?
猜你喜欢
  • 2011-05-18
  • 2022-06-11
  • 2015-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-07
  • 2017-09-04
  • 1970-01-01
相关资源
最近更新 更多