Parallel Task with ASP.NET HttpContext

When using .NET 4.0 Parallel Programming (Check my article) with ASP.NET, you will lose HttpContext once you jump in to another task.
In my case I wanted to get hold of the context from which I wanted to get the current page handler. So I came up with the below code.HOWEVER, and as you can see this is BIG HOWEVER, although I tried the code and it did work I am not 100% sure about it because the idea of manually setting the context (as you will see in a moment) and messing up with the way threading works gives me the creeps! But anyway I thought I would share it:Action action = new Action(dostuff);
Task.Factory.StartNew(action, obj);where:private void dostuff(object obj)
{
IHttpHandler han = ((HttpContext)obj).CurrentHandler;
//do stuff
}or you can use delegates:

Task.Factory.StartNew(new Action(
delegate(object objContext)
{
IHttpHandler han = ((HttpContext)objContext).CurrentHandler;
//do stuff
}
)
, obj);

or event better: lambda:

Task.Factory.StartNew(new Action(
objContext =>
{
IHttpHandler han = ((HttpContext)objContext).CurrentHandler;
//do stuff
}
)
, obj);

Ok so it was a short post, and I thought I would spice it up with some code variations 🙂

Advertisement

2 thoughts on “Parallel Task with ASP.NET HttpContext

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s