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; // 調(diào)整以更改動(dòng)畫(huà)速度
// 禁用按鈕以防止重復(fù)點(diǎn)擊
btnStartTask.Enabled = false;
// 執(zhí)行耗時(shí)任務(wù)并等待完成
await RunLongRunningTaskAsync();
// 還原UI狀態(tài)
progressBar1.Style = ProgressBarStyle.Blocks;
progressBar1.MarqueeAnimationSpeed = 0;
btnStartTask.Enabled = true;
MessageBox.Show("任務(wù)完成!");
}
private async Task RunLongRunningTaskAsync()
{
// 使用 CancellationTokenSource 以便可以取消任務(wù)(可選)
var cts = new CancellationTokenSource();
try
{
// 模擬耗時(shí)任務(wù)
await Task.Run(() =>
{
for (int i = 0; i < 100; i++)
{
// 模擬工作的一部分
Thread.Sleep(50); // 模擬耗時(shí)操作
// 報(bào)告進(jìn)度(可選,用于更新UI進(jìn)度條)
// 這里進(jìn)度條僅僅是示意,因?yàn)槭褂玫氖荕arquee風(fēng)格
this.Invoke(new Action(() =>
{
// 可以根據(jù)需要更新其他UI控件
// progressBar1.Value = i; // 僅對(duì)Blocks風(fēng)格有效
}));
// 檢查是否請(qǐng)求取消
if (cts.Token.IsCancellationRequested)
{
cts.Token.ThrowIfCancellationRequested();
}
}
}, cts.Token);
}
catch (OperationCanceledException)
{
// 任務(wù)取消處理(可選)
MessageBox.Show("任務(wù)已取消。");
}
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 = "開(kāi)始任務(wù)";
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 = "動(dòng)態(tài)等待示例";
this.ResumeLayout(false);
}
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.Button btnStartTask;
}
}arp