Skip to content

Instantly share code, notes, and snippets.

@davidfowl
Last active December 10, 2015 20:08
Show Gist options
  • Save davidfowl/4486482 to your computer and use it in GitHub Desktop.
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.
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