Monday, June 13, 2011

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<object> action = new Action<object>(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<object>(
delegate(object objContext)
{
IHttpHandler han = ((HttpContext)objContext).CurrentHandler;
//do stuff
}
)
, obj);

or event better: lambda:

Task.Factory.StartNew(new Action<object>(
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 :)

2 comments: