using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DynamicWaitingExample
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private async void btnStartTask_Click(object sender, EventArgs e)
{
// 初始化 ProgressBar
progressBar1.Style = ProgressBarStyle.Marquee;
progressBar1.MarqueeAnimationSpeed = 30; // 调整以更改动画速度
// 禁用按钮以防止重复点击
btnStartTask.Enabled = false;
// 执行耗时任务并等待完成
await RunLongRunningTaskAsync();
// 还原UI状态
progressBar1.Style = ProgressBarStyle.Blocks;
progressBar1.MarqueeAnimationSpeed = 0;
btnStartTask.Enabled = true;
MessageBox.Show("任务完成!");
}
private async Task RunLongRunningTaskAsync()
{
// 使用 CancellationTokenSource 以便可以取消任务(可选)
var cts = new CancellationTokenSource();
try
{
// 模拟耗时任务
await Task.Run(() =>
{
for (int i = 0; i < 100; i++)
{
// 模拟工作的一部分
Thread.Sleep(50); // 模拟耗时操作
// 报告进度(可选,用于更新UI进度条)
// 这里进度条仅仅是示意,因为使用的是Marquee风格
this.Invoke(new Action(() =>
{
// 可以根据需要更新其他UI控件
// progressBar1.Value = i; // 仅对Blocks风格有效
}));
// 检查是否请求取消
if (cts.Token.IsCancellationRequested)
{
cts.Token.ThrowIfCancellationRequested();
}
}
}, cts.Token);
}
catch (OperationCanceledException)
{
// 任务取消处理(可选)
MessageBox.Show("任务已取消。");
}
finally
{
// 清理资源
cts.Dispose();
}
}
// 初始化窗体控件
private void InitializeComponent()
{
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.btnStartTask = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// progressBar1
//
this.progressBar1.Location = new System.Drawing.Point(12, 12);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(358, 23);
this.progressBar1.Style = System.Windows.Forms.ProgressBarStyle.Marquee;
this.progressBar1.TabIndex = 0;
//
// btnStartTask
//
this.btnStartTask.Location = new System.Drawing.Point(158, 50);
this.btnStartTask.Name = "btnStartTask";
this.btnStartTask.Size = new System.Drawing.Size(75, 23);
this.btnStartTask.TabIndex = 1;
this.btnStartTask.Text = "开始任务";
this.btnStartTask.UseVisualStyleBackColor = true;
this.btnStartTask.Click += new System.EventHandler(this.btnStartTask_Click);
//
// MainForm
//
this.ClientSize = new System.Drawing.Size(382, 90);
this.Controls.Add(this.btnStartTask);
this.Controls.Add(this.progressBar1);
this.Name = "MainForm";
this.Text = "动态等待示例";
this.ResumeLayout(false);
}
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.Button btnStartTask;
}
}arp