Winform非同步等待控制元件簡單實現
阿新 • • 發佈:2019-02-18
思路
- BaseForm類繼承Form class:通過拓展BaseForm類新增控制元件,使用時繼承BaseForm
- 等待控制元件作用:
- 禁用主窗體控制元件;
- 顯示進度條控制元件
- 非同步呼叫: try{} finally{}進行控制元件的回收
實現
BaseForm
public partial class BaseForm : Form
{
private ProgressBar progressBar = null;
/// <summary>
/// Show ProgressBarControl when waiting...
/// </summary>
public virtual ProgressBar ProgressBarControl
{
get { return this.progressBar; }
set { this.progressBar = value; }
}
public BaseForm()
{
InitializeComponent();
}
}
BaseFormEx
using System;
using System.Collections.Generic;
using System.Diagnostics ;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RoadmapSupporter
{
public static class BaseFormEx
{
public static void BeginWait(this BaseForm baseForm)
{
Debug.Assert(baseForm != null);
baseForm.Invoke((MethodInvoker)delegate
{
baseForm.Enabled = false;
if (baseForm.ProgressBarControl == null)
{
baseForm.ProgressBarControl = new ProgressBar();
baseForm.Controls.Add(baseForm.ProgressBarControl);
baseForm.ProgressBarControl.Size = new Size(246, 36);
baseForm.ProgressBarControl.Name = "progressBar";
baseForm.ProgressBarControl.Visible = true;
baseForm.ProgressBarControl.Style = ProgressBarStyle.Marquee;
baseForm.ProgressBarControl.Location = new Point(baseForm.Width / 2 - baseForm.ProgressBarControl.Width / 2, baseForm.Height / 2 - baseForm.ProgressBarControl.Height);
baseForm.ProgressBarControl.BringToFront();
}
});
}
public static void EndWait(this BaseForm baseForm)
{
Debug.Assert(baseForm != null);
baseForm.Invoke((MethodInvoker)delegate
{
if (baseForm.ProgressBarControl != null)
{
if (baseForm.Controls.Contains(baseForm.ProgressBarControl))
baseForm.Controls.Remove(baseForm.ProgressBarControl);
baseForm.ProgressBarControl.Dispose();
baseForm.ProgressBarControl = null;
baseForm.Enabled = true;
}
});
}
}
}
Call
public partial class RoadmapSupporter : BaseForm
{
public void paradigm{
this.BeginWait();
ThreadPool.QueueUserWorkItem(arg =>
{
try
{
if (CompareInfo(_PublishingToolFileName, _PreviousFileName, ref _Epics))
{
webBrowserShow.DocumentText = FormatEmail(_Epics);
}
else
{
Invoke((MethodInvoker)delegate { MessageBox.Show(this, "An Error occur when comparing epics", "Compare Epics"); });
}
}
finally
{
this.EndWait();
}
});
}
}