开发者

Web Service Singleton object problem

开发者 https://www.devze.com 2023-01-27 14:31 出处:网络
I am creating a singleton object in the first request to the web service and keeping it in the memory.

I am creating a singleton object in the first request to the web service and keeping it in the memory.

This works fine for first few seconds. If I make a request 5 minutes later, I can see that the singleton object is created again? is my singleton object getting disposed after x no of minutes ?

how can i make increase the life-time of my object forever ?

    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();
                    }
            开发者_Go百科        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);
            }
        }


there can be no of reasons but mostly i am thinking about ASPNET process recyling.


Try to derive from MarshalByRefObject and override 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;
}

Read more about LifetimeServices.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号