-
Notifications
You must be signed in to change notification settings - Fork 0
/
AsyncBufferedReader.cs
66 lines (55 loc) · 1.68 KB
/
AsyncBufferedReader.cs
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
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace DropboxStreamUploader
{
public class AsyncBufferedReader
{
readonly Stream _stream;
readonly MemoryStream _buffer = new MemoryStream();
public AsyncBufferedReader(Stream stream)
{
_stream = stream;
}
public async Task Start(int operationBufferSize, CancellationToken cancellation)
{
byte[] operationBuffer = new byte[operationBufferSize];
while (!cancellation.IsCancellationRequested && _stream.CanRead)
{
int read = await _stream.ReadAsync(operationBuffer, 0, operationBufferSize, cancellation);
if (read == 0)
{
await Task.Delay(500, cancellation);
continue;
}
lock (_buffer)
_buffer.Write(operationBuffer, 0, read);
}
}
public int NewDataLength
{
get
{
lock (_buffer) return (int) _buffer.Length;
}
}
public byte[] Buffer { get; private set; }
public int Advance()
{
lock (_buffer)
{
_buffer.Position = 0;
int r;
if ((Buffer != null) && (Buffer.Length >= _buffer.Length))
r = _buffer.Read(Buffer, 0, Buffer.Length);
else
{
Buffer = _buffer.ToArray();
r = Buffer.Length;
}
_buffer.SetLength(0);
return r;
}
}
}
}