Skip to content

Instantly share code, notes, and snippets.

@tugberkugurlu
Forked from davidfowl/Streaming.cs
Created September 4, 2013 07:24
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 tugberkugurlu/6433741 to your computer and use it in GitHub Desktop.
Save tugberkugurlu/6433741 to your computer and use it in GitHub Desktop.
public class Configuration(IAppBuilder app)
{
// TaskCompletionSource
app.Map("/streaming-api1", map =>
{
// Streaming API using SignalR
var connectionContext = GlobalHost.ConnectionManager.GetConnectionContext<RawConnection>();
map.Run(async context =>
{
var tcs = new TaskCompletionSource<object>();
// Whenever a message is sent to this connection we're going to write it to the response
IDisposable disposable = connectionContext.Connection.Receive(async message =>
{
await context.Response.WriteAsync(message.ToString());
await context.Response.Body.FlushAsync();
});
context.Request.CallCancelled.Register(() => tcs.TrySetResult(null));
await tcs.Task;
disposable.Dispose();
});
});
// Awaitable cancelltion tokens
app.Map("/streaming-api2", map =>
{
// Streaming API using SignalR
var connectionContext = GlobalHost.ConnectionManager.GetConnectionContext<RawConnection>();
map.Run(async context =>
{
// Whenever a message is sent to this connection we're going to write it to the response
IDisposable disposable = connectionContext.Connection.Receive(async message =>
{
await context.Response.WriteAsync(message.ToString());
await context.Response.Body.FlushAsync();
});
await context.Request.CallCancelled;
disposable.Dispose();
});
});
}
// Impl
public static class CancellationTokenExtensions
{
public static CancellationTokenAwaiter GetAwaiter(this CancellationToken cancellationToken)
{
return new CancellationTokenAwaiter(cancellationToken);
}
public class CancellationTokenAwaiter : INotifyCompletion
{
private readonly CancellationToken _cancellationToken;
public CancellationTokenAwaiter(CancellationToken cancellationToken)
{
_cancellationToken = cancellationToken;
}
public void GetResult()
{
}
public bool IsCompleted
{
get
{
return _cancellationToken.IsCancellationRequested;
}
}
public void OnCompleted(Action action)
{
_cancellationToken.Register(action);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment