summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Core/LockingSemaphore.cs
blob: fa13150f9806215548ae3608617f257fd7b8031d (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
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace Xamarin.Forms
{
	internal class LockingSemaphore
	{
		static readonly Task Completed = Task.FromResult(true);
		readonly Queue<TaskCompletionSource<bool>> _waiters = new Queue<TaskCompletionSource<bool>>();
		int _currentCount;

		public LockingSemaphore(int initialCount)
		{
			if (initialCount < 0)
				throw new ArgumentOutOfRangeException("initialCount");
			_currentCount = initialCount;
		}

		public void Release()
		{
			TaskCompletionSource<bool> toRelease = null;
			lock (_waiters)
			{
				if (_waiters.Count > 0)
					toRelease = _waiters.Dequeue();
				else
					++_currentCount;
			}
			if (toRelease != null)
				toRelease.TrySetResult(true);
		}

		public Task WaitAsync(CancellationToken token)
		{
			lock (_waiters)
			{
				if (_currentCount > 0)
				{
					--_currentCount;
					return Completed;
				}
				var waiter = new TaskCompletionSource<bool>();
				_waiters.Enqueue(waiter);
				token.Register(() => waiter.TrySetCanceled());
				return waiter.Task;
			}
		}
	}
}