简体   繁体   中英

How to host Windows Service (like) in IIS

How to host a Windows Service in IIS and keep that service runing like it is running on Windows? Could I use some feature from WCF service?

I've not access to the Windows itself, only to IIS. Inside that service I'll create a thread which at scheduled time will process some data.

In short, you can't.

A more detailed answer is that there are 2 problems:

  1. IIS worker processes are launched only when a HTTP request comes in. This means you can't start your service with the system.
  2. IIS worker processes are recycled (ie restarted) on several conditions. For example, a worker process is restarted if no HTTP request comes in for a long time. This means you can't control when your service is shut down, unless you have access to application pool recycling configuration. Keep in mind that the recycling logic only ensures that all pending HTTP requests are complete, but does not await all background threads to complete.

You can come with a partial solution this way:

  1. Create a WCF service method that checks if your long-running thread is alive and if not, starts it.
  2. Create a very simple windows service that periodically (once in 5 seconds) calls that method. Deploy the service somewhere, eg on your own machine.

The only question that remains is: do you really need to avoid windows services? Could you find a place to host the service? There are some use cases when a windows service is the best or even the only way.

You cant, in a nut shell.

However you can make use of the health monitoring API specifically the heartbeat functionality. see:

http://msdn.microsoft.com/en-us/library/system.web.management.webheartbeatevent.aspx

for details on the class you will need to implement to be called when there is work to do

also this answer on SO might help Understanding heartbeat in ASP.NET health monitoring

Once you have implemented a webheartbeatevent derived class you can check your db or what ever you want to check if there is work to do.

A better solution IMHO is to scrap the service entirely and redesign the system to be 100% web based, as services become a deployment and maintenance nightmare. as i assume you are now finding out...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM