I'm new to parallel programming concepts. I'm trying to implement fire-and-forgot kind of method in my project. Somebody please evaluate the below code & let me whether this is thread safe or not.
//Controller
public ActionResult AddMail(Guid userId)
{
EmailNotification.QueueMailAync(userId);
}
//BL
public static class EmailNotification
{
public static void QueueMailAync(Guid userId)
{
HostingEnvironment.QueueBackgroundWorkItem
(
cancellationToken =>
{
try
{
QueueMail(userId);
}
catch (Exception e)
{
logger.Error(e);
}
}
);
}
static void QueueMail(Guid userId)
{
using (var context = new DBEntities())
{
var user = context.Users.FirstOrDefault(u => u.Id == userId);
string body = context.EmailContents.FirstOrDefault().BodyText;
body = body.Replace("{USER_NAME}",user.UserName);
var mail = new ArchOver.Model.Email();
mail.BodyText = body;
mail.UserId = userId;
mail.Subject = "Aync";
mail.EmailTo = user.Person.Email;
context.Users.Add(mail);
context.SaveChanges();
}
}
}