Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Keep Web Service Objects States

0.00/5 (No votes)
26 Mar 2008 1  
keep web service running without users

Introduction

This service keep one web service instance live for a long time.

Background

I recently found here on code project article that explaining "simulation of windows service" by using cache expiring event. You can read it here. And then I came to idea to use it keep my web service alive long time without users.

Using the code

You should make pattern for hitting page as described in article and in your web service implement singleton pattern. Code described in article simulates timer that hitting page every minute. As you can make instance of your web service in you web page first time you visit it and then every next hit will return your instance and will keep your web service alive. So that means that you can use for example timers or other object in your service without fear of loosing their states.

Implement singleton to be sure that you will not make thousands of instances.

    static WebService instance = null;
    static readonly object singletonSync = new object();
    public static WebService Instance
    {
        get
        {
            lock (singletonSync)
            {
                if (instance == null)
                {
                    instance = new WebService();
                }
                return instance;
            }
        }
    }  
// next code goes to global asax 

protected void Application_BeginRequest(Object sender, EventArgs e)
    {
        if (HttpContext.Current.Request.Url.ToString() == defaultUrl)
        {
            NewCacheEntry();
        }
    }

    private void NewCacheEntry()
    {
        if (null != HttpContext.Current.Cache[newCacheItemKey])
        {
            return;
        }

        HttpContext.Current.Cache.Add(
            newCacheItemKey, 
            "value", 
            null, 
            DateTime.MaxValue,
            TimeSpan.FromMinutes(1), 
            CacheItemPriority.NotRemovable,
            new CacheItemRemovedCallback(CacheItemRemoved));

    }

    public void CacheItemRemoved(string key, object value, CacheItemRemovedReason reason)
    {
        CliDownloadThePage();
    }
    private void CliDownloadThePage()
    {
        System.Net.WebClient client = new System.Net.WebClient();
        client.DownloadData(defaultUrl);
    }

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here