Timer in WCF service host - c#

Is it a good idea to initialize a timer to do a periodic task in a WCF service host or will that mess with the lifecycle or performance of the service being hosted?
I have a custom service host that announces it's availability (with the goal of creating a registry for clients) upon starting and stopping. I want to create a timer to do this periodically but my concern is that this will cause problems (I haven't ran into any yet but maybe I haven't stressed it enough or something) or maybe it will eat resources and kill the performance of the service. The idea is to hookup the timer on the OnOpened and OnClosing events, of course.
For what is worth, this service is hosted in IIS so it is IIS the one instantiating and managing the service host.

Is it a good idea to initialize a timer to do a periodic task in a WCF
service host or will that mess with the lifecycle or performance of
the service being hosted?
That will depend on where your WCF service is hosted. If it is hosted inside IIS it might be problematic. The reason for this is because IIS can decide to recycle the ASP.NET application pool at any time and your timer will simply stop working. It is not something you can rely upon. If on the other hand you have hosted your WCF service inside a Windows Service self host, it is fine to use a timer. You may take a look at the following blog post about the dangers of implementing recurring background tasks in ASP.NET hosts.

Related

Keep a WCF Service alive under IIS

i have thoroughly searched the internet (most of the links sent me to stackoverflow ;)) to try to come up with a solution how to keep a WCF Service alive under IIS (7.5).
Many of the responses here were suggesting to write an application that will periodically send dummy requests to the WCF service in order to keep it alive.
My question is:
what if I create a thread in the WCF which will start when a service is first called (in a static constructor) that will periodically consume the WCF itself?
I mean for example in c#:
while (true)
{
WebClient client = new WebClient();
string returnString = client.DownloadString("http://...");
Thread.Sleep(1000 * 5);
}
assuming that "http://..." is an URI to a provided WebMethod which for example returns some integer.
Would that work?
Basically I need some kind of web service (not particulary a WCF but not a Windows Service) that is running on a server that performs some operations and updates something in a SQL Server database. So if the described approach will not work, what might be the best way to achieve this?
Go to your IIS -> Application Pool (or create new one) -> Advanced settings and set Regular Time Interval=0
See related thread here.
AppFabric allows you to create wcf services which can autostart and be long living - this might be worth checking out as a hosting option (it's just a plugin for IIS)
Auto Start
What you are doing is basically wrong from the outset.
The problem is this:
IIS is basically a stateless request broker for http requests (basic IIS) and a request broker for service requests (IIS w. AppFabric).
What you are asking for is how to turn the inherently stateless IIS into a stateful server, with eternal threads running.
That is not what IIS does, IIS handles requests and its AppDomain is subject to AT ALL TIMES be torn down (destorying all threads).
Which makes the most upvoted answer dangerous, as it teaches you how to affect the recycle process, without controlling the tear-downs (off app-domains and threads) that IIS itself will intermittenly perform.
The requester is "foreign" to the IIS itself.
The internal lifetime of the service though, is entirely managed by IIS (and the configuration of its applications) itself.
So if with "keep alive" you mean: to constantly request some service, then do as Andreas suggest further up (create a schedueled job).
If with "keep alive" you mean: to make sure the same instance of the class handles requests, then you need to look into WCF lifetimes.
If with "keep alive" you mean: to make the code you have created "stateful" and keep f.eks static variables alive and so on, well you are not accepting that IIS is basically a stateless pr. request broker with internal lifetime management.
I suggest you create a small program (console app) that calls the web service. The program should take as arguments the url of the web service. Then you create a windows scheduled task that runs the program. In this way you have a lot of flexibility as compared to the embedded approach you are querying about as the program is just another client to the web service.
Try to avoid using while loop. Maybe http://quartznet.sourceforge.net/ is something you are looking for. On WCF start create Task every 10 minutes which will cal WCF itself.

Examples of long-polling in ASP.NET combined with WCF service monitoring?

We have a number of Windows services running in our system (built in C#). We use WCF to communicate with them and control them, since WCF offers very convenient communication with these processes.
Right now in our Windows GUI for managing, monitoring and troubleshooting the services, we simply register callbacks and receive notifications when a message is available from the service. Obviously this application is stateful and WCF provides the ability for the local delegate to be called when the maintained connection to the service indicates.
In our web application which users actually use, we'd like to use long-polling to have a status area on the web page (iframe, AJAX, whatever) which shows any issues which the services are reporting. We'd like to use a long-polling or other technique which minimizes actual polling on the network.
The problem we are running up against is that we need something to make the long-polling HTTP request against which will somehow always be running in IIS and which itself can be WCF-connected to our services and which can convert the event/delegate-based WCF response into a blocking-style long-poll response. It feels like a chicken-and-egg situation that some component in our system is always going to be in a loop, polling - and that's exactly what we are trying to avoid.
Does anyone have an example of doing this?
Well, if your services present with WCF, why not simply consume the WCF services with javsacript? Then you remove your IIS servers from the equation completely. if a user wants to see what the services are doing then they can retrieve the information directly from the service.
Here's a blog with someone showing how to do this:Call wcf service from Json

Injecting services that are expensive to create

I have an application that sends email and fax notifications when an item is complete. My implementation is working but it takes several seconds to construct (i.e. connecting to our servers). This ends up freezing the UI for several seconds until the notification services have been fully constructed and used. I'm already pushing the problem as far as it will go by injecting factories and creating my services at the last possible minute.
What options do I have for injecting external services that takes several seconds to construct? I'm thinking of instructing my container that these services are singletons, which would only construct the services once per application start-up.
Simple solution
I would give those services a longer lifetime (singleinstance).
The problem though is that TCP connections are usually disconnected if nothing have happened for a while. Which means that you need to have some kind of keep alive packets to keep them open.
More robust solution
imho the connection setup is not the problem. Contacting a service should not take long. You haven't specified what the external services are. I'm guessing that they are some kind of web services hosted in IIS. If so, make sure that the application pools aren't recycled too often. Starting a new application in IIS can take time.
The other thought is if you really need to wait for the service to complete? Why not queue the action (to be handled by the thread pool or in a separate thread) and let the user continue? If required, simply use a messagebox when the service have been called and something failed.
These services should be bootstrapped on application startup and then configured via DI using a singleton which is then injected to any classes that use the class in their constructor.
I can recommend Unity or Spring.Net. I've found Unity very easy to use for simple injection, so give that a look.

Create a WCF service hosted in IIS7 alive between request?

How can I keep a WCF service alive between requests?
The service is creating a simple cache in memory on initialisation and I dont want the service to have to re-initialise between requests.
The cache is built up using data extracted from a database and so for efficiency i only need this to be done rarely.
The database is not going to be updated often and so recycling the app pool every night will suffice in terms of updating the cache.
You are asking two questions. If you need service instance alive between requests you should check InstanceContextMode set to PerSession or Single. If you need application initialization to prepare your shared cache you should check IIS 7.5 Warm-up module and place your initialization to Application_Start in Global.asax. For older versions of IIS you have to write some application (console is enough) which will be scheduled to call your web application / service and warm it up.

How to Create a Listener for WCF ServiceHost events when service is hosted under IIS?

I have a WCF service which will be hosted under IIS. Now I have some resources(Connections) that I create within service constructor. I need to free up those resources when IIS which is hosting the service shuts down or resets. These are not the resources that I will be clearing out every time client disconnects but they are application wide resources which will only free up when the service itself or IIS shuts down.
I saw another post where someone mentioned that he has created a listener to capture the events of ServiceHost. Can someone help me with figuring out how to get a handle of the ServiceHost and capture the IIS reset or IIS shutdown event and free up my resources in WCF service?
Well, I'm out of ideas, but I think that this article contains your answer in the chapter: "Accessing ServiceHost in IIS". It seems you need to build your own HostFactory because out of the box IIS uses the standard HostFactory and practically controls the creation and destruction of Hosts. By providing your own HostFactory you can add your own code to control the initialization and destruction...
You can use the IDisposable pattern with finalizer on the class that holds the resources.
On unload of AppDomain, all objects are finalized and if the object that has reference to the resources (such connections) has a finalizer, the finalizer will be called and you can close / dispose the resources at that point.
The whole point of WCF services and IIS hosting is to achieve scalability and allow easy hosting. Although you could connect to events exposed by the ServiceHostBase class (see here), I would recommend against it and analyzing if you really need those shared resources. The main reasons for asking you to re-think are: shared resources need to be thread safe (IIS can serve many requests simultaneously), so this creates a bottleneck for the scalability of your application and secondly, it's best if your services are stateless, and this includes (I guess) the usage of share resources (or application wide resources).

Categories

Resources