【问题标题】:store data in a global collection in WCF将数据存储在 WCF 的全局集合中
【发布时间】:2015-10-01 08:07:17
【问题描述】:

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

我的问题是 - 当我将它存储在全局时,这个集合是否会在呼叫结束时过期(集合 = 空)? 将 .svc 类中的这个全局集合设置为静态 List 就足够了,还是我必须设置 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留在内存/缓存中,直到我将它设置为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 }); 
           }
      }
}

【问题讨论】:

    标签: c# wcf garbage-collection global-variables ram


    【解决方案1】:

    假设您添加到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

    【讨论】:

    • customer 有一个 id 和一个 lastSendDate。我正在通过id 查询以获取日期。检查从该日期到现在经过的时间,并将其与我的设置interval 进行比较。如果经过的时间(以分钟为单位)大于间隔(以分钟为单位),我发送邮件并更新客户lastSendDate。所以这会像我上面的问题一样工作吗?
    • 这个方法在设定的时间只被一个单一的 aspx 站点调用一次 - 这个站点由服务器上的一个计划任务(每 10-15 分钟运行一次)调用,所以我猜它是线程安全的?!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    • 2023-04-08
    相关资源
    最近更新 更多