Statistics
| Branch: | Revision:

root / trunk / Pithos.Core / Agents / AsyncAutoResetEvent.cs @ 79f92570

History | View | Annotate | Download (1.6 kB)

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

    
7
using System.Threading.Tasks;
8

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

    
16
    /// <summary>
17
    /// TODO: Update summary.
18
    /// </summary>
19
    public class AsyncAutoResetEvent
20
    {
21
        private readonly static Task Completed = TaskEx.FromResult(true);
22
        private readonly Queue<TaskCompletionSource<bool>> _waits = new Queue<TaskCompletionSource<bool>>();
23
        private bool _signaled;
24

    
25
        public Task WaitAsync()
26
        {
27
            lock (_waits)
28
            {
29
                if (_signaled)
30
                {
31
                    _signaled = false;
32
                    return Completed;
33
                }
34
                else
35
                {
36
                    var tcs = new TaskCompletionSource<bool>();
37
                    _waits.Enqueue(tcs);
38
                    return tcs.Task;
39
                }
40
            }
41
        }
42

    
43
        public void Set()
44
        {
45
            TaskCompletionSource<bool> toRelease = null;
46
            lock (_waits)
47
            {
48
                if (_waits.Count > 0)
49
                    toRelease = _waits.Dequeue();
50
                else if (!_signaled)
51
                    _signaled = true;
52
            }
53
            if (toRelease != null)
54
                toRelease.SetResult(true);
55
        }
56

    
57
    }
58
}