我有网络应用程序MVC 发送我想要使用Windows服务的电子邮件。
我已在其中一个存储库中实现了邮件发送部分。
这是我的方法
public class MailQueueRepository:IMailQueueRepository
{
private readonly myDbContext _db;
private readonly IMailSender _mailSender;
public MailQueueRepository(myDbContext db, IMailSender mailSender)
{
_db = db;
_mailSender = mailSender;
}
public void SendMails()
{
var mailsToBeSent = _db.MailQueues.Where(a => a.Status == MailStatus.Pending).ToList();
foreach (var mailToBeSent in mailsToBeSent)
{
try
{
mailToBeSent.Status = MailStatus.Sending;
_db.SaveChanges();
_mailSender.SendSmtpMail(mailToBeSent.ToAddress,mailToBeSent.Subject,mailToBeSent.Body);
mailToBeSent.Status = MailStatus.Sent;
mailToBeSent.LastTryDate = DateTime.Now;
_db.SaveChanges();
}
catch (Exception)
{
mailToBeSent.Status = MailStatus.Failed;
mailToBeSent.NumRetries ++;
_db.SaveChanges();
}
}
}
}
我想从Windows服务中调用此函数 这就是我所做的
public partial class MailService : ServiceBase
{
private object _lock = new object();
private static bool RUNNING = false;
private readonly Timer timerTick = null;
private readonly IMailQueueRepository _mailSender;
public MailService()
{
_mailSender = new MailQueueRepository(new myDbContext(), new SmtpMailSender());
int sendInterval = int.Parse(ConfigurationManager.AppSettings["check_interval"].ToString());
timerTick = new Timer(TimeSpan.FromSeconds(sendInterval).TotalMilliseconds);
timerTick.Elapsed += timerTick_Elapsed;
InitializeComponent();
}
private void timerTick_Elapsed(object sender, ElapsedEventArgs e)
{
if (RUNNING) return;
lock (_lock)
{
if (RUNNING) return;
RUNNING = true;
//add try catch here and always unlock
try
{
_mailSender.SendMails();
RUNNING = false;
}
catch (Exception ex)
{
System.Threading.Monitor.Exit(_lock);
}
}
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
if (timerTick != null)
{
timerTick.Start();
}
}
protected override void OnStop()
{
if (timerTick == null) return;
timerTick.Stop();
timerTick.Dispose();
}
}
和Program.cs
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MailService()
};
ServiceBase.Run(ServicesToRun);
}
}
但是现在当我运行这项服务时,我的邮件不会被发送。
我这样做是错误的吗? 该怎么办?