Reputation: 1
I have called thread in master page on page load and called EMail function and it as follows :
Page_load()
{
CreatingThread();
}
protected void CreatingThread()
{
Thread tSendMails;
tSendMails = new System.Threading.Thread(delegate() { EmailQueueSettings(); });
tSendMails.IsBackground = true;
tSendMails.Start();
}
protected void EmailQueueSettings()
{
// Function to get emails which are not sent ;
// looping it and sending it one by one
// Function to send mails
// Updating the status after mail is sent
}
Mails are going but to the same user multiple times mails are sent to them.
Is it possible assign different thread and different mails when a page is loaded next time?
Upvotes: 0
Views: 1923
Reputation: 2165
Actually, re-reading your request and comments. I think I misunderstood your request. I was under the assumption you wanted this to work on page load and run in a different thread to what the user was in. But what you want, is something to constantly be running in the back of a web application, correct?
Generally, what I would do is have a console application in the background doing this. But you could do something along the lines of this, in the global.asax Application_Start
method.
void Application_Start(object sender, EventArgs e)
{
Task beginSendEmailTask = new Task(SendEmailRunningTask);
beginSendEmailTask.Start();
}
void SendEmailRunningTask()
{
while (true)
{
Thread.Sleep(300000); // 5minutes
MailMessage[] emails = GetEmailsToSend();
SmtpClient client = new SmtpClient(); // Configure this
foreach (MailMessage email in emails)
{
client.Send(email);
// Mark email in your database/application as sent.
}
}
}
Don't forget to mark the email as sent, where ever you store them. This could be why you are sending them multiple times. It could also be because it is running for every master page load.
Edit: Explanation
Task Waits 5 Minutes
GetEmailsToSend() finds first 50 out of 100 emails to send.
Iterates and sends the emails
Task Waits 5 Minutes
GetEmailsToSend() finds next 50 out of 100 emails to send.
Iterates and sends the emails
Task Waits 5 Minutes
GetEmailsToSend() finds no emails
Task Waits 5 Minutes
GetEmailsToSend() finds 2 new emails
Iterates and sends the emails
Upvotes: 1