【发布时间】: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