-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsyncEnumerator.cs
More file actions
56 lines (42 loc) · 1.08 KB
/
AsyncEnumerator.cs
File metadata and controls
56 lines (42 loc) · 1.08 KB
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
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace PictureView;
class AsyncEnumerator<T> : IDisposable
{
private readonly IEnumerator<T> source;
private readonly SemaphoreSlim moveNextSem, asyncTaskSem;
public bool MovedNext { get; private set; }
public T Current => source.Current;
public AsyncEnumerator(IEnumerable<T> enumerable)
{
moveNextSem = new SemaphoreSlim(0);
asyncTaskSem = new SemaphoreSlim(0);
source = enumerable.GetEnumerator();
Task.Run(MoveNextHandle);
}
private async Task MoveNextHandle()
{
do
{
await asyncTaskSem.WaitAsync();
MovedNext = source.MoveNext();
moveNextSem.Release();
} while (MovedNext);
}
public void Dispose()
{
source.Dispose();
}
public async Task<bool> MoveNext()
{
asyncTaskSem.Release();
await moveNextSem.WaitAsync();
return MovedNext;
}
public void Reset()
{
source.Reset();
}
}