-
-
Save tugberkugurlu/6433741 to your computer and use it in GitHub Desktop.
This file contains 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
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