Skip to content

Instantly share code, notes, and snippets.

@karno
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karno/59074dc3f2e445a3f2bc to your computer and use it in GitHub Desktop.
Save karno/59074dc3f2e445a3f2bc to your computer and use it in GitHub Desktop.
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