Advertisement
Guest User

Untitled

a guest
Jan 31st, 2015
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. using (var reader = new CancellableStreamReader(stream))
  2. {
  3. while (true)
  4. {
  5. cancellationToken.ThrowIfCancellationRequested();
  6.  
  7. // create timeout cancellation token source
  8. using (var timeoutTokenSource = new CancellationTokenSource(readTimeout))
  9. using (var compositeTokenSource = CancellationTokenSource.CreateLinkedTokenSource(
  10. cancellationToken, timeoutTokenSource.Token))
  11. {
  12. // execute read line
  13. var line = await reader.ReadLineAsync(compositeTokenSource.Token).ConfigureAwait(false);
  14. if (String.IsNullOrEmpty(line))
  15. {
  16. System.Diagnostics.Debug.WriteLine("#USERSTREAM# CONNECTION CLOSED.");
  17. break;
  18. }
  19.  
  20. // read operation completed successfully
  21. Task.Run(() => DispatchStreamingElements(DynamicJson.Parse(line), handler),
  22. cancellationToken).ConfigureAwait(false);
  23. }
  24. }
  25.  
  26. // more performant?
  27. using (var timeoutTokenSource = new CancellationTokenSource())
  28. using (var compositeTokenSource = CancellationTokenSource.CreateLinkedTokenSource(
  29. cancellationToken, timeoutTokenSource.Token))
  30. {
  31. while (true)
  32. {
  33. cancellationToken.ThrowIfCancellationRequested();
  34.  
  35. // create timeout cancellation token source
  36. // execute read line
  37. var readTask = reader.ReadLineAsync(compositeTokenSource.Token);
  38. if (await Task.WhenAny(readTask, Task.Delay(readTimeout, compositeTokenSource.Token))
  39. .ConfigureAwait(false) == readTask)
  40. {
  41. var line = readTask.Result;
  42. // read operation completed successfully
  43. Task.Run(() => DispatchStreamingElements(DynamicJson.Parse(line), handler),
  44. cancellationToken).ConfigureAwait(false);
  45. }
  46. else
  47. {
  48. timeoutTokenSource.Cancel();
  49. System.Diagnostics.Debug.WriteLine("#USERSTREAM# CONNECTION CLOSED.");
  50. break;
  51. }
  52. }
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement