Why is threading so much work in a Web app?
Doing stuff in seperate threads in a Web app is a pain when you need a reference to general application state. Why does it have to be so hard?
The first time I did something in this realm, I was trying to make an asynchronous mailer to notify people in a forum thread that there was a reply to the thread. With some help from someone in the ASP.NET forums, I eventually arrived at something like this in the class (the GCHandle class is in System.Runtime.InteropServices, if you're curious):
public void Send()
{
appHandle = GCHandle.Alloc(HttpContext.Current, GCHandleType.Normal);
// notify by email those who are hooked up
ThreadStart workerstart = new ThreadStart(Mailer);
Thread myThread = new Thread(workerstart);
myThread.Start();
}
protected GCHandle appHandle;
private void Mailer()
{
HttpContext context = (HttpContext)appHandle.Target;
// mail work here
}
This works perfectly, though I'm still not clever enough to understand exactly why. Adapting this same logic to a static Timer object in an HttpModule wasn't much harder, provided I kept passing along the context through whatever objects and code I wanted to run:
public void Init(HttpApplication application)
{
appHandle = GCHandle.Alloc(application.Context, GCHandleType.Normal);
myTimer = new Timer(new TimerCallback(this.TimerMethod), application.Context, 60000, 60000);
}
static Timer myTimer;
protected GCHandle appHandle;
private void TimerMethod(object sender)
{
HttpContext context = (HttpContext)appHandle.Target;
// do whatever
}
So now that I'm clever enough to follow this pattern, can anyone explain why exactly it works? I'm not satisfied without knowing the "why" along with the "how."