Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / AsyncManualResetEvent.cs @ 303596f9

History | View | Annotate | Download (1.5 kB)

1
// -----------------------------------------------------------------------
2
// <copyright file="AsyncManualResetEvent.cs" company="Microsoft">
3
// TODO: Update copyright text.
4
// </copyright>
5
// -----------------------------------------------------------------------
6

    
7
using System.Threading;
8
using System.Threading.Tasks;
9

    
10
namespace Pithos.Core.Agents
11
{
12
    using System;
13
    using System.Collections.Generic;
14
    using System.Linq;
15
    using System.Text;
16

    
17
    /// <summary>
18
    /// TODO: Update summary.
19
    /// </summary>
20
    public class AsyncManualResetEvent
21
    {
22
        private volatile TaskCompletionSource<bool> _tcs;
23

    
24
        public AsyncManualResetEvent()
25
        {
26
            _tcs = new TaskCompletionSource<bool>();
27
        }
28

    
29
        public AsyncManualResetEvent(bool signalled)
30
        {            
31
            _tcs = new TaskCompletionSource<bool>();
32
            if (signalled)
33
                _tcs.SetResult(true);
34
        }
35
        public Task WaitAsync() { return _tcs.Task; }
36

    
37
        public void Wait()
38
        {            
39
            _tcs.Task.Wait();
40
        }
41

    
42
        public void Set() { _tcs.TrySetResult(true); }
43

    
44
        public void Reset()
45
        {
46
            while (true)
47
            {
48
                var tcs = _tcs;
49
                if (!tcs.Task.IsCompleted ||
50
                    Interlocked.CompareExchange(ref _tcs, new TaskCompletionSource<bool>(), tcs) == tcs)
51
                    return;
52
            }
53
        }
54
    }
55
}