Create a WCF service hosted in IIS7 alive between request? - c#

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.

Related

Timer in WCF 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?
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.

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.

Recycling WCF Web Service on IIS

Is it possible to recycle a WCF web service hosted on IIS from code?
When a certain error code is received from an Oracle connection I am using, I want to recycle the web service.
If you jus want to recycle your current application then try
HttpRuntime.UnloadAppDomain();
it will unload your app from host's memory and will load again on next request.
from MSDN
UnloadAppDomain is useful for servers that have a large number of
applications that infrequently receive requests. Rather than keep
application resources alive for the lifetime of the process,
UnloadAppDomain allows programmatic shutdown of unused applications.

WCF - Optimize Config and IIS

I have a WCF RESTful service that is hosted in IIS that is hit by several of our applications. The WCF services appear to operate fine for the most part, but sometimes it takes a long time to get a response from the service.
I was seeing if there was a good tutorials or resources to follow on how to best configure WCF RESTful services to be web scale either through the web.config, from IIS, or from our dedicated application pool.
We have gone through our services and used NHibernate profiler to find and optimize any problematic queries and we also have memcached setup to also help with performance. The problem seems to be when many applications are consuming the service in a short period of time or when the service has sat idle for a long period of time.
Thanks for any assistance.
Not sure if its applicable to your scenario, but I read the below mentioned blog post on MSDN a couple of days ago. It's about a problem in the Net IOCP Threadpool which causes long response times for WCF when many requests are issued in short time. Maybe that could help you?
WCF scales up slowly with bursts of work
KB2538826
There is no general advice on heavy load issue, but one of the possible optimizations would be using asynchronous operations on the server side: Scale WCF Application Better with Asynchronous Programming. It's about conserving thread pool resources while making database calls.
As for the idle period issue, check out Configuring Recycling Settings for an Application Pool (IIS 7)

WCF communication between 2 servers crashes after IIS7 process recycle

I am kind of stumped with this one, and was hoping I could find some answers here.
Basically, I have an ASP.NET application that is running across 2 servers. Server A has all of the business logic/data access exposed as web services, and Server B has the website which talks to those services (via WCF, with net.tcp binding).
The problem occurs a few seconds after a recycle of my app pool is initiated by IIS on Server A. The recycle happens after the allotted time (using the default of 29 hours set in IIS).
In the server log (of Server A):
A worker process with process id of
'####' serving application pool
'AppPoolName' has requested a recycle
because the worker process reached its
allowed processing time limit.
I believe that this is normal behavior. The problem is that a few seconds later, I get this exception on Server B:
This channel can no longer be used to
send messages as the output session
was auto-closed due to a
server-initiated shutdown. Either
disable auto-close by setting the
DispatchRuntime.AutomaticInputSessionShutdown
to false, or consider modifying the
shutdown protocol with the remote
server.
This doesn't happen on every recycle; I assume that it happens when someone is hitting the site with a request WHILE the recycle happens.
Furthermore, my application is down until I intervene; this exception continues to occur every time a subsequent request is made to the page. I intervene by editting the web.config (by adding a space or something benign to the end of file) and saving it- I assume that that causes my application to recompile and brings the services back up. I also have experimented with running a batch file that does this for me every time the exception happens ;)
Now, I could barely find any information on this exception, and I've been looking for a while. Most of the information I did find pertains to WCF settings that I am not using.
I already read up on "DispatchRuntime.AutomaticInputSessionShutdown" and I don't think it pertains to this situation. This particular property refers to the service shutting down automatically in response to behavior on the client side, which is not what is happening here. Here, the service is shutdown because of IIS.
I did read this which went through some sort of work around to bring the service back up automatically, but I am really looking to understand what is going on here, not to hack around it!
I have started playing around with the settings in IIS7, specifically turning on/off Overlapped Recycling and increasing the process startup/shutdown times. I am wondering whether it is safe to turn off recycling completely (I believe if I put 0 for the recycling time interval?) But again, I want to know what's going on!
Anyway, if you need more information, let me know. Thanks in advance!
This is probably related to how you open and close WCF connections.
If you open a proxy when your app starts and then continue to use this, a break in the connection, which is caused by a restart on the server side. Results in a error on the client side, since the server that the proxy was talking to is no longer there.
When you restart the client side (changing the web.config) new proxies are created against a server that is running.
The way to fix this is to make sure that you close a WCF connection after you use it.
http://www.codeguru.com/csharp/.net/net_wcf/article.php/c15941/
You should also make sure that you're using the correct SessionMode for your Web Service. I remember having similar trouble with some of my Services until I sorted out the correct mode. This is especially true when you're mixing this with any other authentication mode that is not "None".
This link might have some pointer.
http://msdn.microsoft.com/en-us/library/ms731193.aspx
My suggestion is to simply stop using IIS to host your services. Unless there is something you really need from IIS, I would recommend just writing a standard Windows Service to host your WCF endpoints.
If you can't do that, then by all means turn off recycling. AppPool recycling is mainly there because web developers write crappy code. I know that sounds rather blunt, but if you have enough sense to write code that doesn't leak then there is no reason to have IIS constantly restart your program.

Categories

Resources