using System;
using System.Threading;
using System.Windows.Forms;
namespace ProgressBarExample
{
public class Form1 : Form
{
private ProgressBar progressBar1;
private Button startButton;
public Form1()
{
// 初始化进度条和按钮
progressBar1 = new ProgressBar();
startButton = new Button();
// 设置进度条的属性
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
progressBar1.Value = 0;
progressBar1.Step = 1;
// 设置按钮的属性并添加点击事件
startButton.Text = "Start";
startButton.Click += new EventHandler(StartButton_Click);
// 将控件添加到窗体中
this.Controls.Add(progressBar1);
this.Controls.Add(startButton);
}
private void StartButton_Click(object sender, EventArgs e)
{
// 创建一个新线程来模拟长时间运行的任务
Thread thread = new Thread(new ThreadStart(RunLongTask));
thread.Start();
}
private void RunLongTask()
{
for (int i = 0; i <= 100; i++)
{
// 更新进度条的值
if (progressBar1.InvokeRequired)
{
progressBar1.Invoke(new Action(() => progressBar1.Value = i));
}
else
{
progressBar1.Value = i;
}
// 模拟任务处理时间
Thread.Sleep(50);
}
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Form
,并在其中添加了一个 ProgressBar
和一个 Button
。Thread
来模拟长时间运行的任务,并通过 Invoke
方法更新 UI 线程中的进度条值。Main
方法中启动应用程序。这个示例展示了如何在 C# WinForms 应用程序中使用进度条,并通过多线程技术确保 UI 的响应性。
上一篇:c# cancellationtokensource
下一篇:c# 位运算
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站