-
Notifications
You must be signed in to change notification settings - Fork 7
/
LoadingHelper.cs
94 lines (78 loc) · 2.34 KB
/
LoadingHelper.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using System;
using System.Threading;
namespace StudentPhotoCollection
{
class LoadingHelper
{
#region 相关变量定义
/// <summary>
/// 定义委托进行窗口关闭
/// </summary>
private delegate void CloseDelegate();
private static LoadingForm loadingForm;
private static readonly Object syncLock = new Object(); //加锁使用
#endregion
/// <summary>
/// 显示loading框,使用者调用
/// </summary>
public static void ShowLoadingForm()
{
// Make sure it is only launched once.
if (loadingForm != null)
return;
Thread thread;
try
{
thread = new Thread(new ThreadStart(LoadingHelper.ShowForm))
{
IsBackground = true
};
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
catch (Exception)
{
thread = null;
}
}
/// <summary>
/// 关闭loading框,使用者调用
/// </summary>
public static void CloseLoadingForm()
{
Thread.Sleep(50); //可能到这里线程还未起来,所以进行延时,可以确保线程起来,彻底关闭窗口
if (loadingForm != null)
{
lock (syncLock)
{
Thread.Sleep(50);
if (loadingForm != null)
{
Thread.Sleep(50); //通过三次延时,确保可以彻底关闭窗口
loadingForm.Invoke(new CloseDelegate(LoadingHelper.CloseForm));
}
}
}
}
/// <summary>
/// 显示窗口
/// </summary>
private static void ShowForm()
{
LoadingHelper.CloseForm();
loadingForm = new LoadingForm();
loadingForm.ShowDialog();
}
/// <summary>
/// 关闭窗口
/// </summary>
private static void CloseForm()
{
if (loadingForm != null)
{
loadingForm.CloseForm();
loadingForm = null;
}
}
}
}