aboutsummaryrefslogtreecommitdiff
path: root/SocketHttpListener/Net/HttpStreamAsyncResult.cs
blob: e7e516c6b45d44a517d1b6a8e96e273c58613d2e (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
using System;
using System.Threading;
using System.Threading.Tasks;

namespace SocketHttpListener.Net
{
    internal class HttpStreamAsyncResult : IAsyncResult
    {
        private object _locker = new object();
        private ManualResetEvent _handle;
        private bool _completed;

        internal readonly object _parent;
        internal byte[] _buffer;
        internal int _offset;
        internal int _count;
        internal AsyncCallback _callback;
        internal object _state;
        internal int _synchRead;
        internal Exception _error;
        internal bool _endCalled;

        internal HttpStreamAsyncResult(object parent)
        {
            _parent = parent;
        }

        public void Complete(Exception e)
        {
            _error = e;
            Complete();
        }

        public void Complete()
        {
            lock (_locker)
            {
                if (_completed)
                    return;

                _completed = true;
                if (_handle != null)
                    _handle.Set();

                if (_callback != null)
                    Task.Run(() => _callback(this));
            }
        }

        public object AsyncState
        {
            get { return _state; }
        }

        public WaitHandle AsyncWaitHandle
        {
            get
            {
                lock (_locker)
                {
                    if (_handle == null)
                        _handle = new ManualResetEvent(_completed);
                }

                return _handle;
            }
        }

        public bool CompletedSynchronously
        {
            get { return (_synchRead == _count); }
        }

        public bool IsCompleted
        {
            get
            {
                lock (_locker)
                {
                    return _completed;
                }
            }
        }
    }
}