C#执行耗时进程时显示动态等待效果实现
|
admin
2024年11月27日 18:47
本文热度 477
|
在C#中,当执行耗时操作时,显示一个动态等待效果(如一个旋转的图标或进度条)可以提升用户体验。以下是一个简单的实现示例,使用 Task
, CancellationToken
, 和 ProgressBar
控件(或者你可以自定义任何动态效果控件)。
示例步骤:
创建Windows Forms应用程序:
- 使用Visual Studio创建一个新的Windows Forms应用程序。
添加控件:
- 在主窗体上添加一个
ProgressBar
控件(可以选择添加一个 Label
控件来显示文本信息)。 - 你也可以自定义一个动态效果的控件,比如一个旋转的图标。
编写代码:
- 使用异步编程来执行耗时操作,并在UI线程中更新动态等待效果。
示例代码:
以下是一个完整的示例代码,演示了如何实现动态等待效果。
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 = "动态等待示例";
this.ResumeLayout(false);
}
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.Button btnStartTask;
}
}arp
关键点:
异步编程:
- 使用
async
和 await
关键字来避免阻塞UI线程。 - 使用
Task.Run
将耗时操作放到后台线程执行。
UI更新:
- 使用
this.Invoke
方法确保UI更新在UI线程中执行。
取消支持:
- 使用
CancellationTokenSource
以便在需要时可以取消任务。
ProgressBar控件:
- 使用
ProgressBarStyle.Marquee
实现动态效果。
通过以上步骤,你可以在C# Windows Forms应用程序中实现一个简单的动态等待效果,使用户在等待耗时操作时有良好的体验。
该文章在 2024/11/27 18:47:17 编辑过