Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using (var reader = new CancellableStreamReader(stream))
- {
- while (true)
- {
- cancellationToken.ThrowIfCancellationRequested();
- // create timeout cancellation token source
- using (var timeoutTokenSource = new CancellationTokenSource(readTimeout))
- using (var compositeTokenSource = CancellationTokenSource.CreateLinkedTokenSource(
- cancellationToken, timeoutTokenSource.Token))
- {
- // execute read line
- var line = await reader.ReadLineAsync(compositeTokenSource.Token).ConfigureAwait(false);
- if (String.IsNullOrEmpty(line))
- {
- System.Diagnostics.Debug.WriteLine("#USERSTREAM# CONNECTION CLOSED.");
- break;
- }
- // read operation completed successfully
- Task.Run(() => DispatchStreamingElements(DynamicJson.Parse(line), handler),
- cancellationToken).ConfigureAwait(false);
- }
- }
- // more performant?
- using (var timeoutTokenSource = new CancellationTokenSource())
- using (var compositeTokenSource = CancellationTokenSource.CreateLinkedTokenSource(
- cancellationToken, timeoutTokenSource.Token))
- {
- while (true)
- {
- cancellationToken.ThrowIfCancellationRequested();
- // create timeout cancellation token source
- // execute read line
- var readTask = reader.ReadLineAsync(compositeTokenSource.Token);
- if (await Task.WhenAny(readTask, Task.Delay(readTimeout, compositeTokenSource.Token))
- .ConfigureAwait(false) == readTask)
- {
- var line = readTask.Result;
- // read operation completed successfully
- Task.Run(() => DispatchStreamingElements(DynamicJson.Parse(line), handler),
- cancellationToken).ConfigureAwait(false);
- }
- else
- {
- timeoutTokenSource.Cancel();
- System.Diagnostics.Debug.WriteLine("#USERSTREAM# CONNECTION CLOSED.");
- break;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement