Web Service Singleton对象问题

时间:2010-12-01 10:35:01

标签: c# asp.net web-services

我在对Web服务的第一个请求中创建一个单例对象并将其保留在内存中。

这可以在最初几秒内正常工作。如果我在5分钟后发出请求,我可以看到再次创建单例对象? x我没有分钟后,我的单身对象被处理掉了吗?

如何才能永远延长我对象的生命周期?

    public sealed class Singleton
    {
        static ServerInstance instance = null;
        static readonly object padlock = new object();

        Singleton() {
        }

        public static ServerInstance Instance {
            get {
                lock (padlock) {
                    if (instance == null) {
                        instance = new ServerInstance();
                    }
                    return instance;
                }
            }
        }
        ~Singleton()
        {
          #if DEBUG
                  ExceptionFactory.Fatal("~Singleton() called!");
          #endif
        }
    }


    [WebMethod]
    public string OnReceiveEvent(string objectXmlData, string objectType) {

        if (!Singleton.Instance.initServerComplete) {
            InitServer();
        }

       return Singleton.Instance.OnReceiveEvent(objectXmlData, objectType);
    }


 public void InitServer() {
            if (!Singleton.Instance.initServerComplete) {
                Singleton.Instance.InitServer();
                Singleton.Instance.initServerComplete = true;

                GC.KeepAlive(Singleton.Instance);
            }
        }

2 个答案:

答案 0 :(得分:2)

可能没有任何原因,但主要是我在考虑ASPNET流程重新编制。

答案 1 :(得分:0)

尝试从MarshalByRefObject派生并覆盖InitializeLifetimeService

public override Object InitializeLifetimeService()
{
  ILease lease = (ILease)base.InitializeLifetimeService();
  if (lease.CurrentState == LeaseState.Initial)
  {
     lease.InitialLeaseTime = TimeSpan.FromMinutes(100);
     lease.SponsorshipTimeout = TimeSpan.FromMinutes(100);
     lease.RenewOnCallTime = TimeSpan.FromSeconds(100);
  }
  return lease;
}

详细了解LifetimeServices