/
UnitySynchronizationContext.cs
90 lines (77 loc) · 1.91 KB
/
UnitySynchronizationContext.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
using System;
using System.Collections.Generic;
using System.Threading;
public enum ExecutionType
{
Post,
Send
}
public struct SendOrPostCallbackItem
{
object _state;
private ExecutionType _exeType;
SendOrPostCallback _method;
public SendOrPostCallbackItem(SendOrPostCallback callback,
object state, ExecutionType type)
{
_method = callback;
_state = state;
_exeType = type;
}
public void Execute()
{
if (_method == ExecutionType.Send)
Send();
else
Post();
}
public void Send()
{
_method(mState);
}
public void Post()
{
_method(mState);
}
}
public class UnitySynchronizationContext : SynchronizationContext, IDisposable
{
public Queue<SendOrPostCallbackItem> Queue1;
public Queue<SendOrPostCallbackItem> Queue2;
public UnitySynchronizationContext()
: base()
{
Queue1 = new Queue<SendOrPostCallbackItem>();
Queue2 = new Queue<SendOrPostCallbackItem>();
}
public override void Send(SendOrPostCallback d, object state)
{
SendOrPostCallbackItem item = new SendOrPostCallbackItem(d, state,
ExecutionType.Send);
Queue2.Enqueue(item);
}
public override void Post(SendOrPostCallback d, object state)
{
SendOrPostCallbackItem item = new SendOrPostCallbackItem(d, state,
ExecutionType.Post);
Queue2.Enqueue(item);
}
public void Run()
{
while (Queue1.Count > 0)
{
SendOrPostCallbackItem workItem = Queue1.Dequeue();
workItem.Execute();
}
var tmpQ = Queue1;
Queue1 = Queue2;
Queue2 = tmpQ;
}
public void Dispose()
{
}
public override SynchronizationContext CreateCopy()
{
return this;
}
}