using System;
using System.Threading;
namespace Mesnac.Action.ChemicalWeighing
{
public class LoadingHelper
{
#region 相关变量定义
///
/// 定义委托进行窗口关闭
///
private delegate void CloseDelegate();
private static Loading loadingForm;
private static readonly Object syncLock = new Object(); //加锁使用
#endregion
///
/// 显示loading框
///
public static void ShowLoadingScreen()
{
// Make sure it is only launched once.
if (loadingForm != null)
return;
Thread thread = new Thread(new ThreadStart(LoadingHelper.ShowForm));
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
///
/// 显示窗口
///
private static void ShowForm()
{
if (loadingForm != null)
{
loadingForm.CloseOrder();
loadingForm = null;
}
loadingForm = new Loading();
loadingForm.TopMost = true;
loadingForm.ShowDialog();
}
///
/// 关闭窗口
///
public static void CloseForm()
{
Thread.Sleep(50); //可能到这里线程还未起来,所以进行延时,可以确保线程起来,彻底关闭窗口
if (loadingForm != null)
{
lock (syncLock)
{
Thread.Sleep(50);
if (loadingForm != null)
{
Thread.Sleep(50); //通过三次延时,确保可以彻底关闭窗口
loadingForm.Invoke(new CloseDelegate(LoadingHelper.CloseFormInternal));
}
}
}
}
///
/// 关闭窗口,委托中使用
///
private static void CloseFormInternal()
{
loadingForm.CloseOrder();
loadingForm = null;
}
}
}