Multi Threading in ASP.NET
One of the applications I'm writing needs to call web services to sen data off to a third part, however the user doesn't need to see any kind of response from these web services, so what I wanted to do was fire off the web service calls in a different thread and return the page to the user while the web services are still being called.
This was great, until I came to need something from the HttpContext in my web service call, when using threads in ASP.NET the HttpContext is only avalibale to the main thread, and not to any child threads without some clever trickery.
Here's the methodology I've used to sort it: -
(Source: http://www.codecomments.com/ASP_.NET/message351969.html )
MyThreadClass T = new MyThreadClass();
T.User = System.Web.HttpContext.Current.User.Identity.Name;
T.StartThread();
using System;
using System.Threading;
namespace Private
{
public class MyThreadClass
{
//Public Property to store the Username
private string _User = String.Empty;
public string User
{
get
{
return _User;
}
set
{
_User = value;
}
}
//Public method to start the Thread going.
public void StartThread()
{
System.Threading.Thread T = new System.Threading.Thread(new System.Threading.ThreadStart(Run));
T.Start();
}
//Private method that actuall does stuff, in this case e-mails the User property to me.
private void Run()
{ BusinessProcesses.Emails.Send("phil@winstanley.name","phil@winstanley.name",String.Empty,"Thread",_User,System.Web.Mail.MailFormat.Text);
}
public MyThreadClass()
{
}
}
}