ui/wpf/UIcore/Application.cs

changeset 78
135920fe441b
child 81
5eb765a7a793
equal deleted inserted replaced
77:bc0ed99e49c7 78:135920fe441b
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading;
6 using System.Threading.Tasks;
7
8 namespace UI
9 {
10 public class Application
11 {
12 private static Application instance;
13
14 private System.Windows.Application application;
15
16 private Thread thread;
17 private Queue<Action> queue = new Queue<Action>();
18 private object sync = new object();
19 private object result = new object();
20
21 private Boolean Running = false;
22 public String Name;
23
24 private Application() : base()
25 {
26 thread = new Thread(() => Run());
27 thread.SetApartmentState(ApartmentState.STA);
28 thread.Start();
29 }
30
31 public static Application GetInstance()
32 {
33 if (instance == null)
34 {
35 instance = new Application();
36 GC.KeepAlive(instance);
37 }
38 return instance;
39 }
40
41 public Thread Start()
42 {
43 lock(sync)
44 {
45 queue.Enqueue(() => RunApplication());
46 Monitor.Pulse(sync);
47 }
48 return thread;
49 }
50
51 private void RunApplication()
52 {
53 application = new System.Windows.Application();
54 application.Run();
55 }
56
57 public void Run()
58 {
59 lock(sync)
60 {
61 for (;;)
62 {
63 Monitor.Wait(sync);
64 Action action = queue.Dequeue();
65 action.Invoke();
66 lock (result)
67 {
68 Monitor.Pulse(result);
69 }
70 }
71 }
72 }
73
74 public T Exec<T>(Func<T> func)
75 {
76 ResultExec<T> e = new ResultExec<T>();
77 e.Func = func;
78
79 if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
80 {
81 e.Exec();
82 return e.Result;
83 }
84 else
85 {
86 lock (sync)
87 {
88 queue.Enqueue(() => e.Exec());
89 Monitor.Pulse(sync);
90 }
91 lock (result)
92 {
93 Monitor.Wait(result);
94 }
95
96 return e.Result;
97 }
98 }
99
100 public void Exec(Action action)
101 {
102 if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
103 {
104 action.Invoke();
105 }
106 else
107 {
108 lock (sync)
109 {
110 queue.Enqueue(action);
111 Monitor.Pulse(sync);
112 }
113 lock (result)
114 {
115 Monitor.Wait(result);
116 }
117 }
118 }
119 }
120
121 public class ResultExec<T>
122 {
123 public T Result;
124 public Func<T> Func;
125
126 public void Exec()
127 {
128 Result = Func.Invoke();
129 }
130 }
131
132 public class VoidExec
133 {
134 public Action Action;
135
136 public void Exec()
137 {
138 Action.Invoke();
139 }
140 }
141 }

mercurial