Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Re: Multi-threading in a web service

Re: Multi-threading in a web service

Scheduled Pinned Locked Moved C#
helptutorialquestion
7 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Offline
    M Offline
    mjmcinto
    wrote on last edited by
    #1

    I've got a service that is dependent on some files, and checks for modification of the files (thanks to everyone who helped me understand how to do this). Now that I've got that done, I think it would be nice to be able to have another thread whose sole responsibility is to check the time stamp on these files and reload the data when needed, that way the users don't have to wait while data is reloadedl My initial thought is to either create another thread and have it sleep or use timers to accomplish this, however I do not know where to place this code in my service. I don't think I would want to put it in the constructor otherwise it would get called whenever anyone made a request, and would result in mutliple threads doing the same thing. Is there anyway to create a new thread when the service starts up (before the initial request) that will do this? Thanks for your help.

    A H 2 Replies Last reply
    0
    • M mjmcinto

      I've got a service that is dependent on some files, and checks for modification of the files (thanks to everyone who helped me understand how to do this). Now that I've got that done, I think it would be nice to be able to have another thread whose sole responsibility is to check the time stamp on these files and reload the data when needed, that way the users don't have to wait while data is reloadedl My initial thought is to either create another thread and have it sleep or use timers to accomplish this, however I do not know where to place this code in my service. I don't think I would want to put it in the constructor otherwise it would get called whenever anyone made a request, and would result in mutliple threads doing the same thing. Is there anyway to create a new thread when the service starts up (before the initial request) that will do this? Thanks for your help.

      A Offline
      A Offline
      Andy Brummer
      wrote on last edited by
      #2

      [edit]Doh. read web service as windows service. Please disregard. [/edit] The system.timers.Timer is good for this. Add the timer to your service object. Then set the interval and assign the event in your constructor. Then you just need to start and stop the timer in your service start and stop events. If you need to make absolutely sure that the timer will not be executing after you leave the stop event , you need to do your own thread syncronization, but in most cases you don't need to worry about it. If you need to schedule multiple jobs look for the scheduled timer CP article I posted a few weeks ago.


      If you don't kill me you will only make me stronger That and a cup of coffee will get you 2 cups of coffee

      1 Reply Last reply
      0
      • M mjmcinto

        I've got a service that is dependent on some files, and checks for modification of the files (thanks to everyone who helped me understand how to do this). Now that I've got that done, I think it would be nice to be able to have another thread whose sole responsibility is to check the time stamp on these files and reload the data when needed, that way the users don't have to wait while data is reloadedl My initial thought is to either create another thread and have it sleep or use timers to accomplish this, however I do not know where to place this code in my service. I don't think I would want to put it in the constructor otherwise it would get called whenever anyone made a request, and would result in mutliple threads doing the same thing. Is there anyway to create a new thread when the service starts up (before the initial request) that will do this? Thanks for your help.

        H Offline
        H Offline
        Heath Stewart
        wrote on last edited by
        #3

        I don't remember if you're the same guy I and nother guy were helping before, but look at the Cache class in the .NET Framework. You can access this in your Web Service using the Context property (HttpContext), which gives you the Cache object. You can add a CacheDependency on that file so that if it changes the cached item is invalidated, so that you read-load the data. If you look at the documentation for the Cache.Add method, however, you'd notice a CacheItemRemovedCallback parameter (the last parameter). If you didn't want to have the user wait until the data is reloaded, you could add a callback that loads the data as soon as the cache item is invalidated and removed from the cache.

        Microsoft MVP, Visual C# My Articles

        M 1 Reply Last reply
        0
        • H Heath Stewart

          I don't remember if you're the same guy I and nother guy were helping before, but look at the Cache class in the .NET Framework. You can access this in your Web Service using the Context property (HttpContext), which gives you the Cache object. You can add a CacheDependency on that file so that if it changes the cached item is invalidated, so that you read-load the data. If you look at the documentation for the Cache.Add method, however, you'd notice a CacheItemRemovedCallback parameter (the last parameter). If you didn't want to have the user wait until the data is reloaded, you could add a callback that loads the data as soon as the cache item is invalidated and removed from the cache.

          Microsoft MVP, Visual C# My Articles

          M Offline
          M Offline
          mjmcinto
          wrote on last edited by
          #4

          Yes that was me, and thank you for your help. I've got the call back working to where it will remove the cached data on a change. However, in the method that does that, I also try to reload and then re-add the data, but it doesn't re-add. Here is the method: public void TPMDataRemovedCallback(String k, Object v, CacheItemRemovedReason r){ TPMreason = r; string tpmDataKey = "TPMDATA"; if(onTPMDataRemove == null) onTPMDataRemove = new CacheItemRemovedCallback (this.TPMDataRemovedCallback); DateTime NoAbsoluteExpiration = Cache.NoAbsoluteExpiration; TimeSpan NoSlidingExpiration = Cache.NoSlidingExpiration; CacheItemPriority Priority = CacheItemPriority.AboveNormal; Context.Cache.Remove(tpmDataKey); System.IO.FileInfo fileInfo = new System.IO.FileInfo(tpmFileName); tpmData = tpm.LoadTPM(); try{ Context.Cache.Add(tpmDataKey,this.tpmData,this.tpmDataCacheDependency,NoAbsoluteExpiration,NoSlidingExpiration,Priority,onTPMDataRemove); } catch(System.Exception caught){ Console.WriteLine("Exception == " + caught); } } I don't see an exception get caught, but the cache at Context.Cache[tpmDataKey] doesn't contain anything. What am I doing wrong?

          H 1 Reply Last reply
          0
          • M mjmcinto

            Yes that was me, and thank you for your help. I've got the call back working to where it will remove the cached data on a change. However, in the method that does that, I also try to reload and then re-add the data, but it doesn't re-add. Here is the method: public void TPMDataRemovedCallback(String k, Object v, CacheItemRemovedReason r){ TPMreason = r; string tpmDataKey = "TPMDATA"; if(onTPMDataRemove == null) onTPMDataRemove = new CacheItemRemovedCallback (this.TPMDataRemovedCallback); DateTime NoAbsoluteExpiration = Cache.NoAbsoluteExpiration; TimeSpan NoSlidingExpiration = Cache.NoSlidingExpiration; CacheItemPriority Priority = CacheItemPriority.AboveNormal; Context.Cache.Remove(tpmDataKey); System.IO.FileInfo fileInfo = new System.IO.FileInfo(tpmFileName); tpmData = tpm.LoadTPM(); try{ Context.Cache.Add(tpmDataKey,this.tpmData,this.tpmDataCacheDependency,NoAbsoluteExpiration,NoSlidingExpiration,Priority,onTPMDataRemove); } catch(System.Exception caught){ Console.WriteLine("Exception == " + caught); } } I don't see an exception get caught, but the cache at Context.Cache[tpmDataKey] doesn't contain anything. What am I doing wrong?

            H Offline
            H Offline
            Heath Stewart
            wrote on last edited by
            #5

            Did you step through your code and see if this method even gets called? You must first call this method (or a similar one) to load the data into the cache and create the callback.

            Microsoft MVP, Visual C# My Articles

            M 1 Reply Last reply
            0
            • H Heath Stewart

              Did you step through your code and see if this method even gets called? You must first call this method (or a similar one) to load the data into the cache and create the callback.

              Microsoft MVP, Visual C# My Articles

              M Offline
              M Offline
              mjmcinto
              wrote on last edited by
              #6

              Yes, I've stepped through the method. It gets called, and there is something on the cache when it gets called. Once that method is called the remove succeeds, as does the loading of the data. However when I call add it doesn't seem to add it to the cache, however upon the next request it sees that there is nothing on the cache, loads the data, and readds it with no problem, and what I don't understand is that I call add then with the same parameters as I do in the RemovedCallback method, only this time it does add it.

              H 1 Reply Last reply
              0
              • M mjmcinto

                Yes, I've stepped through the method. It gets called, and there is something on the cache when it gets called. Once that method is called the remove succeeds, as does the loading of the data. However when I call add it doesn't seem to add it to the cache, however upon the next request it sees that there is nothing on the cache, loads the data, and readds it with no problem, and what I don't understand is that I call add then with the same parameters as I do in the RemovedCallback method, only this time it does add it.

                H Offline
                H Offline
                Heath Stewart
                wrote on last edited by
                #7

                First, you shouldn't call Cache.Remove: the callback is invoked after the item - and remember there could be multiple objects in the cache with different keys - is removed, but you need to be mindful of the key. The following example should work:

                // Somewhere in your constructor or some other
                // initialization method call CacheFile with the appropriate key
                private const string KEY1 = "File1.txt";
                private const string KEY2 = "File2.txt";
                private void CacheFile(string key)
                {
                if (key == null) throw new ArgumentNullException("key");
                if (key.Length == 0) throw new ArgumentException("Invalid key.");
                if (Cache[key] == null)
                {
                string path = Server.MapPath("/docs/" + key);
                using (StreamReader reader = new StreamReader(path))
                {
                Cache.Add(
                key,
                reader.ReadToEnd(),
                new CacheDependency(path),
                Cache.NoAbsoluteExpiration,
                Cache.NoSlidingExpiration,
                CacheItemPriority.AboveNormal,
                new CacheItemRemovedCallback(CacheItemRemoved));
                }
                }
                }
                private void CacheItemRemoved(string key, object value,
                CacheItemRemovedReason reason)
                {
                if (key == KEY1) CacheFile(KEY1);
                else if (key == KEY2) CacheFile(KEY2);
                // else: must've been something else - the point is to check the 'key'
                }
                public string File1Content
                {
                get
                {
                CacheFile(KEY1);
                return Cache[KEY1];
                }
                }
                public string File2Content
                {
                get
                {
                CacheFile(KEY2);
                return Cache[KEY2];
                }
                }

                Microsoft MVP, Visual C# My Articles

                1 Reply Last reply
                0
                Reply
                • Reply as topic
                Log in to reply
                • Oldest to Newest
                • Newest to Oldest
                • Most Votes


                • Login

                • Don't have an account? Register

                • Login or register to search.
                • First post
                  Last post
                0
                • Categories
                • Recent
                • Tags
                • Popular
                • World
                • Users
                • Groups