Client.ExecuteAsync在保存到数据库之前丢失可变数据

时间:2016-06-27 05:45:57

标签: c# asp.net-mvc asynchronous entity-framework-6 mailgun

我有以下代码向多个email id发送电子邮件,并使用RestSharp请求并回复MailGun API

var emodel = model as EmailViewModel;
var context = HttpContext.Current;
var from = "KG <" + emodel.FromEmail[0] + ">";
var client = new RestClient
{
      BaseUrl = new Uri("https://api.mailgun.net/v3"),
      Authenticator = new HttpBasicAuthenticator("api", WebConfigurationManager.AppSettings["MGKey"])
};

foreach(var to in emodel.EmailID) 
{
    var request = new RestRequest();
    request.AddParameter("domain",
    "domain.com", ParameterType.UrlSegment);
    request.Resource = "{domain}/messages";
    request.AddParameter("from", from);
    request.AddParameter("subject", emodel.Subject ? ? "No Subject");
    var body = emodel.Message ? ? "Empty Message";
    request.AddParameter("html", body);
    request.Method = Method.POST;
    request.AddParameter("to", to);
    var json = new JavaScriptSerializer();

    client.ExecuteAsync(request, r => {
      var content = json.Deserialize<Dictionary<string,string >>(r.Content);
      if (content != null && r.ResponseStatus == ResponseStatus.Completed && r.StatusCode == HttpStatusCode.OK) 
      {
          msgId=content.msgID;
      }
      if (msgId != "") 
      {
          using(_db = new DBcontext()) 
          {
              var message = new tblMsg {
                    MDSent = DateTime.Today.Date,
                    MMsg = WebUtility.HtmlEncode(emodel.Message),
                    MMsgStatus = EventTypes.Stored.ToString(),
                    MMsgType = true,
                    MSByID = from,
                    MSByUser = loggedInUser,
                    MSID = msgId,
                    MSub = emodel.Subject ? ? "No subject",
                    MToID = to
              };
              _db.Entry(message).State = EntityState.Added;
              _db.SaveChanges();
          }
      }
      else {
        LogError.LogMessage(r.ErrorMessage, context);
      }
  });
}

EmailViewModel.cs

public class EmailViewModel
{
    public string[] EmailID { get; set; }
    public SelectList Emails { get; set; }

    public string[] Names { get; set; }

    public string Message { get; set; }

    public string[] FromEmail { get; set; }
    public SelectList FromEmails { get; set; }

    public bool HasAttachment { get; set; }
    public string AttachmentPath { get; set; }
    public int AttachmentCount { get; set; }

    public string Subject { get; set; }
}

此处的问题是,当我向多个ID发送电子邮件时,由于client.ExecuteAsync行位于for-loop内,它会多次获取async响应并将其存储在{ {1}}并且在content记录保存到数据库之前,它将被message的下一个async响应替换,因此只有一条记录保存在数据库中。在C#中是否有任何机制,其中我可以保存变量消息值,直到它保存到数据库?我尝试在API变量上使用lock,但它没有帮助..希望找到一些帮助。

0 个答案:

没有答案