在C#中,當執(zhí)行耗時操作時,顯示一個動態(tài)等待效果(如一個旋轉(zhuǎn)的圖標或進度條)可以提升用戶體驗。以下是一個簡單的實現(xiàn)示例,使用 Task
, CancellationToken
, 和 ProgressBar
控件(或者你可以自定義任何動態(tài)效果控件)。
示例步驟:
?創(chuàng)建Windows Forms應用程序?:
- 使用Visual Studio創(chuàng)建一個新的Windows Forms應用程序。
?添加控件?:
- 在主窗體上添加一個
ProgressBar
控件(可以選擇添加一個 Label
控件來顯示文本信息)。 - 你也可以自定義一個動態(tài)效果的控件,比如一個旋轉(zhuǎn)的圖標。
?編寫代碼?:
- 使用異步編程來執(zhí)行耗時操作,并在UI線程中更新動態(tài)等待效果。
示例代碼:
以下是一個完整的示例代碼,演示了如何實現(xiàn)動態(tài)等待效果。
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)
{
progressBar1.Style = ProgressBarStyle.Marquee;
progressBar1.MarqueeAnimationSpeed = 30;
btnStartTask.Enabled = false;
await RunLongRunningTaskAsync();
progressBar1.Style = ProgressBarStyle.Blocks;
progressBar1.MarqueeAnimationSpeed = 0;
btnStartTask.Enabled = true;
MessageBox.Show("任務完成!");
}
private async Task RunLongRunningTaskAsync()
{
var cts = new CancellationTokenSource();
try
{
await Task.Run(() =>
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(50);
this.Invoke(new Action(() =>
{
}));
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();
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;
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);
this.ClientSize = new System.Drawing.Size(382, 90);
this.Controls.Add(this.btnStartTask);
this.Controls.Add(this.progressBar1);
this.Name = "MainForm";
this.Text = "動態(tài)等待示例";
this.ResumeLayout(false);
}
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.Button btnStartTask;
}
}arp
關(guān)鍵點:
?異步編程?:
- 使用
async
和 await
關(guān)鍵字來避免阻塞UI線程。 - 使用
Task.Run
將耗時操作放到后臺線程執(zhí)行。
?UI更新?:
- 使用
this.Invoke
方法確保UI更新在UI線程中執(zhí)行。
?取消支持?:
- 使用
CancellationTokenSource
以便在需要時可以取消任務。
?ProgressBar控件?:
- 使用
ProgressBarStyle.Marquee
實現(xiàn)動態(tài)效果。
通過以上步驟,你可以在C# Windows Forms應用程序中實現(xiàn)一個簡單的動態(tài)等待效果,使用戶在等待耗時操作時有良好的體驗。
該文章在 2024/11/27 18:47:17 編輯過