Skip to content

Instantly share code, notes, and snippets.

@grumpydev
Last active December 14, 2015 09:19
Show Gist options
  • Save grumpydev/5064018 to your computer and use it in GitHub Desktop.
Save grumpydev/5064018 to your computer and use it in GitHub Desktop.
Async Demo
A long running async request will be executed and until it is complete
a series of '*' characters should appear every 0.5 seconds. If this was
executed syncronously then the main thread would block and no characters
would appear.
Running: ***********************************************************************
*****************************************************
Result:
11:18:28 : Before Hook Delay
11:18:33 : Delay 1
11:18:34 : Delay 2
11:18:35 : Executing async http client
11:18:35 : Response: <!DOCTYPE html>
11:18:35 : After Hook Delay
11:18:40 : After Hook Complete
namespace Nancy.Demo.Async
{
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class MainModule : NancyModule
{
public MainModule()
{
Before += async (ctx, ct) =>
{
this.AddToLog("Before Hook Delay\n");
await Task.Delay(5000);
return null;
};
After += async (ctx, ct) =>
{
this.AddToLog("After Hook Delay\n");
await Task.Delay(5000);
this.AddToLog("After Hook Complete\n");
ctx.Response = this.GetLog();
};
Get["/", true] = async (x, ct) =>
{
this.AddToLog("Delay 1\n");
await Task.Delay(1000);
this.AddToLog("Delay 2\n");
await Task.Delay(1000);
this.AddToLog("Executing async http client\n");
var client = new HttpClient();
var res = await client.GetAsync("http://nancyfx.org");
var content = await res.Content.ReadAsStringAsync();
this.AddToLog("Response: " + content.Split('\n')[0] + "\n");
return (Response)this.GetLog();
};
}
private void AddToLog(string logLine)
{
if (!this.Context.Items.ContainsKey("Log"))
{
this.Context.Items["Log"] = string.Empty;
}
this.Context.Items["Log"] = (string)this.Context.Items["Log"] + DateTime.Now.ToLongTimeString() + " : " + logLine;
}
private string GetLog()
{
if (!this.Context.Items.ContainsKey("Log"))
{
this.Context.Items["Log"] = string.Empty;
}
return (string)this.Context.Items["Log"];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment