Last active
December 10, 2015 20:08
-
-
Save davidfowl/4486482 to your computer and use it in GitHub Desktop.
Concurrent request middleware (only works on ASP.NET because I'm lazy). Also does not support websocket requests.
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
private class ConcurrentRequestViewer | |
{ | |
private readonly Func<IDictionary<string, object>, Task> _next; | |
private static ConcurrentDictionary<string, Task> _requests = new ConcurrentDictionary<string, Task>(); | |
public ConcurrentRequestViewer(Func<IDictionary<string, object>, Task> next) | |
{ | |
_next = next; | |
} | |
public Task Invoke(IDictionary<string, object> env) | |
{ | |
var path = (string)env["owin.RequestPath"]; | |
if (path.EndsWith("/requests")) | |
{ | |
var writer = new StreamWriter((Stream)env["owin.ResponseBody"]); | |
using (writer) | |
{ | |
writer.Write("<pre>"); | |
foreach (var req in _requests) | |
{ | |
if (!req.Value.IsCompleted) | |
{ | |
writer.WriteLine(req.Key); | |
} | |
} | |
writer.Write("</pre>"); | |
} | |
var tcs = new TaskCompletionSource<object>(); | |
tcs.SetResult(null); | |
return tcs.Task; | |
} | |
var context = (HttpContextBase)env[typeof(HttpContextBase).FullName]; | |
string url = context.Request.RawUrl; | |
Task task = _next(env); | |
_requests.TryAdd(url, task); | |
task.ContinueWith(_ => | |
{ | |
// Remove the task when it's complete | |
Task t; | |
_requests.TryRemove(url, out t); | |
}); | |
return task; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment