Reputation: 7621
I have an ASP.NET page which sends an email to a list of of users - this list can be fairly large, and we find the ASP.NET page will often timeout.
What we want to do is send these emails in a new thread, so the ASP.NET page refreshes to the user while the email process is working in the background.
I'm having a bit of a hard time getting my head around what I need to do though. Here's the button click event on my ASP.NET page currently:
protected void btnSend_Click(object sender, EventArgs e)
{
//Populate form data session
_FormInfo = new Dictionary<string, string>();
_FormInfo.Add("Name", txtName.Text);
_FormInfo.Add("Postcode", txtPostcodeDone.Text);
PostcodeSearcher.PostcodeEmailer(_Companies, _FormInfo);
mv.ActiveViewIndex = 3;
}
And here's the method I want to call (inside the PostcodeSearcher class)
public static void PostcodeEmailer(List<Company> companies, Dictionary<string, string> quote)
{
...
}
As you can see the method I need to call in a new thread needs to accept parameters - all I can find online is for calling a new thread without parameters. Any ideas?
Upvotes: 1
Views: 438
Reputation: 1112
Beware the problem of IIS killing the ASP.NET application process, IIS can do that if there are no active user requests for the app (after some delay, which is 20min by default). This means that your background thread can be killed before it finishes it work of sending emails and the user won't know about that.
To overcome this problem you can simulate a user request so the runtime doesn't kill the app. Other option (better but more work) is creating a separate process (e.g. a Windows 'Background' Service) that will get a command from the ASP.NET app (using e.g. a WCF service) and will send the emails to users. For easy creation of Windows Services see e.g. http://topshelf-project.com/
See more about this problem: How to optionally run some code on a background thread?
Upvotes: 1
Reputation: 16149
Use the Task functionality of C# as found here. These are very useful for doing async commands (and are quite simple to implement).
EDIT:
Task postcodeTask = new Task(() => PostcodeSearcher.PostcodeEmailer(_Companies, _FormInfo));
postcodeTask.Start();
Upvotes: 0