如果在WinForm中执行一个长时间操作时,窗体就会被锁死,直到操作完成,对于操作者的体验就是死锁状态,那在.NET(.net 5以后)中,怎么实现一个并发,等待,且同步操作信息窗口呢?
第一步:首先定义一个等待窗体,为了有明确的提示,做一个等待的gif图,同步有提示信息。
using System.Windows.Forms;
namespace AliWorkbench.Load
{
partial class LoadingFrm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LoadingFrm));
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.labMessage = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// pictureBox1
//
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(171, 12);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(148, 136);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
//
// labMessage
//
this.labMessage.AutoSize = true;
this.labMessage.Location = new System.Drawing.Point(169, 196);
this.labMessage.Name = "labMessage";
this.labMessage.Size = new System.Drawing.Size(137, 12);
this.labMessage.TabIndex = 1;
this.labMessage.Text = "正在加载中,请等待……";
//
// LoadingFrm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(513, 248);
this.Controls.Add(this.labMessage);
this.Controls.Add(this.pictureBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "LoadingFrm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Loading";
this.TopMost = true;
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Label labMessage;
}
}
为了外部的实时更新提示信息,定义一个Message属性,来更新内容的提示信息控件,这里用的是this.Invoke,因为UI线程有可能与执行线程不相同。同理,当关闭窗体时,也需要处理一下。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AliWorkbench.Load
{
public partial class LoadingFrm : Form
{
public LoadingFrm()
{
InitializeComponent();
}
public string Message
{
set
{
if (labMessage.InvokeRequired)
{
Action action = delegate () { labMessage.Text = value; };
labMessage.Invoke(action);
}
}
}
public void CloseAll()
{
if (this.InvokeRequired)
{
//这里利用委托进行窗体的操作,避免跨线程调用时抛异常,后面给出具体定义
CONSTANTDEFINE.SetUISomeInfo UIinfo = new CONSTANTDEFINE.SetUISomeInfo(new Action(() =>
{
while (!this.IsHandleCreated)
{
;
}
if (this.IsDisposed)
return;
if (!this.IsDisposed)
{
this.Dispose();
}
}));
this.Invoke(UIinfo);
}
else
{
if (this.IsDisposed)
return;
if (!this.IsDisposed)
{
this.Dispose();
}
}
}
}
class CONSTANTDEFINE
{
public delegate void SetUISomeInfo();
}
}
第二步:定义一个等待窗体的管理类,主要有三个成员:1、Show(),是在一个线程中;2、Message属性,是设置窗体的属性,这里需要判断窗体是否存在,不存在就等待,其实可以定义重试次数,避免错误调用顺序,设置属性也是在一个线程中执行;3、Close()也是在线程中,也需要判断窗体是否存在。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AliWorkbench.Load
{
public static class LoadingManage
{
static LoadingFrm _loading;
public static void Show()
{
Task.Run(() =>
{
_loading = new LoadingFrm();
_loading.ShowDialog();
});
}
public static void Close()
{
Task.Run(() =>
{
while (_loading == null || _loading.IsDisposed)
{
Thread.Sleep(10);
}
_loading.CloseAll();
});
}
public static string Message
{
set
{
while (_loading == null || _loading.IsDisposed)
{
Thread.Sleep(10);
}
Task.Run(() =>
{
_loading.Message = value;
});
}
}
}
}
封装后,调用就简单了,如下,首先Show(),然后执行密集服务,在执行过程中,可以更新Message属性,最后执行完就可以Close()了。
LoadingManage.Show();
for (var i = 0; i < 30; i++)
{
LoadingManage.Message = $"正在执行第{i}条数据……";
Thread.Sleep(1000);
}
LoadingManage.Close();