c# - 每次通过 smtp 发送邮件时如何增加变量
问题描述
我有一个邮件程序,代码如下:
private static int i=0;
protected void btnSubmit_Click(object sender, EventArgs e)
{
++i; //i want to increment this variable
{
SendHTMLMail();
}
void SendHTMLMail()
{
StreamReader reader = new StreamReader(Server.MapPath("~/one.html"));
string readFile = reader.ReadToEnd();
string myString = "";
myString = readFile;
MailMessage Msg = new MailMessage();
Msg.From = new MailAddress(txtUsername.Text);
Msg.To.Add(txtTo.Text);
Msg.Subject = txtSubject.Text;
Msg.Body = myString.ToString();
Msg.IsBodyHtml = true;
if (fuAttachment.HasFile)
{
string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
Msg.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
}
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(txtUsername.Text, txtpwd.Text);
smtp.EnableSsl = true;
smtp.Send(Msg);
Msg = null;
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
// Request both failure and success report
Msg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.OnSuccess;
int emailsSent = 0;
try
{
Console.WriteLine("start to send email ...");
smtp.Send(Msg);
emailsSent++;
Console.WriteLine("email was sent successfully!");
}
catch (Exception ex)
{
Console.WriteLine("failed to send email with the following error:");
Console.WriteLine(ex.Message);
}
}
}
在上面的代码中,我有一个变量“i”,我想在每次发送邮件时递增它。现在我面临的问题是,只有当我在 localhost 中的 aspx 页面打开时我一次又一次地发送邮件时,'i'才会增加。一旦我关闭我的 aspx 页面,重新打开它并再次发送邮件,变量“i”就会再次增加到 1,而不是说 4 或 5。
解决方案
放置此代码的位置会发生行为变化。如果它在 ASPX 页面中,那么每当运行时重新编译该页面时,您都会丢失静态数据。如果它在 DLL 文件中,那么只要应用程序/IIS 池回收,您就会丢失值。您需要将最终值保存到持久存储(即数据库)中。下次你需要它们时,你必须从数据库中检索,增加它然后再次保存。请注意,Web 应用程序是多线程的,静态变量不是线程安全的。如果两个线程同时修改同一个变量,您将陷入混乱。使用锁定机制访问多线程应用程序中的静态变量。
推荐阅读
- r - 将列名分配给df,阻止字符自动转换为数字?
- r - 如何分组一个data.frame每个整数行?
- javascript - 无法读取未定义的属性“swaggerUi”
- mysql - MySQL:使用联合将多个选择查询拆分到各自的表中
- html - 在播放预加载视频
- python - 使用 SWIG 将 numpy 数组元素(int)传递给 c++ int
- html - 网页中的越南字体渲染不正确
- java - 在netbeans自动生成的代码问题swing gui jframe
- html - 是什么阻止了白色字体颜色的工作?
- r - 如何在ggplot中使用分组箱形图将geom_text标签放置在正确的位置