Last active
August 29, 2015 14:14
-
-
Save karno/59074dc3f2e445a3f2bc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment