summaryrefslogtreecommitdiff
path: root/Erika/Assets/ConsolePro/Remote/LiteNetLib/NetThread.cs
blob: cdd433f655b16d2aa51165d1670779b57cee17d3 (plain)
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
95
96
97
#if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA
#if WINRT && !UNITY_EDITOR
#define USE_WINRT
#endif

using System;
using System.Threading;

#if USE_WINRT
using Windows.Foundation;
using Windows.System.Threading;
using Windows.System.Threading.Core;
#endif

namespace FlyingWormConsole3.LiteNetLib
{
    public sealed class NetThread
    {
#if USE_WINRT
        private readonly ManualResetEvent _updateWaiter = new ManualResetEvent(false);
        private readonly ManualResetEvent _joinWaiter = new ManualResetEvent(false);
#else
        private Thread _thread;
#endif

        private readonly Action _callback;

        public int SleepTime;
        private bool _running;
        private readonly string _name;

        public bool IsRunning
        {
            get { return _running; }
        }

        public NetThread(string name, int sleepTime, Action callback)
        {
            _callback = callback;
            SleepTime = sleepTime;
            _name = name;
        }

        public void Start()
        {
            if (_running)
                return;
            _running = true;
#if USE_WINRT
            var thread = new PreallocatedWorkItem(ThreadLogic, WorkItemPriority.Normal, WorkItemOptions.TimeSliced);
            thread.RunAsync().AsTask();
#else
            _thread = new Thread(ThreadLogic)
            {
                Name = _name,
                IsBackground = true
            };
            _thread.Start();
#endif
        }

        public void Stop()
        {
            if (!_running)
                return;
            _running = false;

#if USE_WINRT
            _joinWaiter.WaitOne();
#else
            _thread.Join();
#endif
        }

#if USE_WINRT
        private void ThreadLogic(IAsyncAction action)
        {
            while (_running)
            {
                _callback();
                _updateWaiter.WaitOne(SleepTime);
            }
            _joinWaiter.Set();
        }
#else
        private void ThreadLogic()
        {
            while (_running)
            {
                _callback();
                Thread.Sleep(SleepTime);
            }
        }
#endif
    }
}
#endif