GouthamAnand
asked on
How to make 2 threads run safely same block of code one after the other?
Hi,
I have 3 threads running in my windows service application. If any exception in any of the threads, they have to send the email.
Below is my email code.
If the error occurs more than 2 threads at the same time, only one thread is able to send the email. Other 2 are failing and saying - "An asynchronous call is already in progress. It must be completed or canceled before you can call this method."
what is the best way to handle and make the 3 thread use the same block of code without any problems? (if the error occurs in 3 thread at the same time)
I have 3 threads running in my windows service application. If any exception in any of the threads, they have to send the email.
Below is my email code.
public static void SendMail(string machineName, string serviceName, string threadName, string errrorDesc)
{
Object syncLock = new Object();
lock (syncLock)
{
try
{
mm.Subject = _eMailTpltXML.Root.Element("Subject").Value.Replace("##MachineName##", machineName);
mm.Subject = mm.Subject.Replace("##ServiceName##", serviceName);
mm.Subject = mm.Subject.Replace("##ThreadName##", threadName);
mm.Body = _eMailTpltXML.Root.Element("Body").Value;
mm.Body = mm.Body.Replace("##MachineName##", machineName);
mm.Body = mm.Body.Replace("##ServiceName##", serviceName);
mm.Body = mm.Body.Replace("##ThreadName##", threadName);
mm.Body = mm.Body.Replace("##ErrorDesc##", errrorDesc);
sc.Send(mm);
Logger.log.Info(serviceName + " - Email has been sent.");
}
catch (Exception ex)
{
Logger.log.Error("SendEmail - " + ex.Message);
}
}
}
If the error occurs more than 2 threads at the same time, only one thread is able to send the email. Other 2 are failing and saying - "An asynchronous call is already in progress. It must be completed or canceled before you can call this method."
what is the best way to handle and make the 3 thread use the same block of code without any problems? (if the error occurs in 3 thread at the same time)
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
It worked for me.Thanks a lot.
ASKER