将数据存储在WCF的全局集合中



我有一个由ASP调用的WCF。NET应用程序每10-15分钟通过电子邮件通知客户有关的东西。我需要集合来识别已经向哪个用户发送了邮件。因此,如果下一个呼叫来了,我可以查询这个集合,如果邮件是之前发送的,什么时候是最后一次(我设置了一个间隔,这样用户就不会每隔10-15分钟收到邮件)。

我的问题是-当我存储它全局这个集合过期时调用结束(集合=空)?是否足以在。svc类中设置此全局集合为静态列表,或者我是否必须设置DataMember属性?代码会是怎样的呢?

呢?

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
      }
}

这个lastSendUserList留在ram/缓存,直到我将其设置为null(或服务器重启等),所以我可以查询它每次调用进来?或者这个列表在每次调用结束时都被gc清除?

编辑

所以新的代码是这样的?!

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 }); 
           }
      }
}

假设您添加到lastSendUserList,它将始终可用,直到IIS停止/重新启动您的工作进程。

希望customerLastSendDate !!

另外,你应该修剪最后一个,这样它就不会太大了。所以我的代码看起来像。

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);
}

既然你在WCF服务中,你必须是线程安全的。这就是为什么我在lastSendUserList周围有一个lock

最新更新