简体   繁体   中英

store data in a global collection in WCF

I've a WCF which is called by a ASP.NET application every 10-15 Minutes to inform customer via email about stuff. I need the collection to recognize to which user the mail already has been sent. So if the next call is coming in i can query this collection if the mail was send before and when was the last time (i set an interval so the user doesn't get the mail every 10-15 minutes).

My question is - when i store it global does this collection expire when the call ends (collection = empty)? Is it enough to set this global collection in .svc class as static List or do i have to set the DataMember attribute? How would the code look for that?

Like that?

public class Service1 : IService1
{
      private static List<customer> lastSendUserList = new List<customer>();

      void SendMail(int customerid)
      {
           lastSendUserList.FirstOrDefault(x => x.id == customerid);
           .
           // proof date etc. here and send or send not
      }
}

Does this lastSendUserList stay in ram/cache until i set it to null (or server restart etc.) so i can query it every time the call comes in? Or does this list gets cleared by gc everytime when the call ends?

EDIT

So the new Code would look like this?!

public class Service1 : IService1
{
      private static List<customer> lastSendUserList = new List<customer>();

      void SendMail(int customerid, int setInterval)
      {
           customer c;
           c = lastSendUserList.FirstOrDefault(x => x.id == customerid);

           if(c != null && c.lastSendDate + setInterval > DateTime.Now)
           {
                lastSendUserList.Remove(x => x.id == c.id);

                // start with sending EMAIL

                lastSendUserList.Add(new customer() { id = customerid, lastSendDate = DateTime.Now }); 
           }
      }
}

Assuming that you add to lastSendUserList it will be always available until IIS stops/restarts you worker process.

Hopefully customer has LastSendDate !!!

Also, you should trim the last so that it doesn't get too big. So my code would look something like.

TimeSpan const ttl = TimeSpan.FromMinutes(15);
lock (lastSendUserList)
{
  lastSendUserList.Remove(x => x.lastSendDate + ttl < DateTime.Now);
  if (lastSendUserList.Any(x => x.id == customerid))
     return;
}

// ... send the email

lock (lastSendUserList)
{
      customer.lastSendDate = DateTime.Now;
      lastSendUserList.Add(c);
}

Since you are in a WCF service, you have to be thread-safe. That why I have a lock around lastSendUserList .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM