How to make WCF Service with a background worker thread? - wcf

I have a WCF service that all clients connect to in order to get notifications \ reminders (using a CALLBACK interface they implement). Currently the WCF service is self-hosted, but the plan is to have it hosted in a Windows Service.
The WCF service has a 'Publish', 'Subscribe' and 'Unsubscribe' operations.
I need to have a background worker thread of some sort poll an SQL server database table constantly [every XXX minutes], and look for certain 'reminder' rows. Once it finds them - it should notify all the connected clients.
I thought of 2 ways of achieving this.
.
METHOD A :
Have a separate EXE project (don't want it to be a console, so what should it be - a Windows Service ?) that will start and run a background thread. The background thread will connect to the 'Reminder' service as one of its clients. The background thread will poll the database, and once it finds something - it will send a 'Publish' message to the WCF service, that will make the WCF service send the reminder to all the subscribed clients.
.
METHOD B :
Somehow make the background thread run within the WCF service project, and when it detects a new reminder row in the database, somehow make it 'signal' the WCF service with the info, and the WCF service will then send this info to all subscribed clients.
.
Which method is better ? Any other suggestions ?

If this is a long running process, a windows service is the perfect solution.
Your main Win Service thread will be polling the DB, queuing the results into some kind of supplier/consumer thread safe collection.
You can host a WCF service within the win service, which can then consume (remove) any results from the queue and pass them back to the client as requested (calls into the WCF will come in on their own thread)
This is a pretty common architecture, and not difficult to implement.

Method A:
If you were to create two separate hosts (i.e. one for the WCF service and one for the "Polling" service) then you really have only one option to make it all work nicely.
Windows Service communication is very limited (without the help of a service endpoint, e.g. WCF). Therefor, if you were to host your "Polling" service in a Windows Service, you must couple it with a WCF service anyway.
It is then feasible to host both services together in one Windows Service and by manually instantiating the WCF host and passing into the constructor a "Polling" service.
protected override void OnStart(string[] args)
{
//...
// This would be you "polling" service that would start a background thread to poll the db.
var notificationHost = new PollingService();
// This is your WCF service which you will be "self hosted".
var serviceHost = new WcfService(notificationHost);
new ServiceHost(serviceHost).Open();
//...
}
This is far from ideal because you need to communicate via events between the two services, plus your WCF service must run on singleton mode for manual instantiation to work... So this leaves you with...
Method B:
If you were to host the "Polling" services inside your WCF service, you are going to run into a number of issues.
You need to be aware of the number of instances of the "Polling" services that gets created. If your WCF service has been configured to be instantiated for every session, you could end up with too many "Polling" services and that may end up killing your db/servers.
To avoid the first issue, you may need to set a singleton WCF service, which may lead to a scaling issue in the near future where one WCF service instance is not enough to handle the number of connection requests.
Method C:
Given the drawbacks in Method A and B, the best solution would be to host two independent WCF services.
This is your regular service where you have subscriber/unsubscribe/publish.
This is your polling singleton service with subscribe/unsubscribe.
The idea is that your regular service, upon receiving a subscriber will open a new connection to your polling service or use an existing one (depending on how you configure your session) and wait for a reply. Your polling service is a long running WCF service that polls your db and publish the notification to its subscribers (i.e. the other WCF host).
Pros:
You are assured that there will be only one polling service.
You could scale your solution to host the regular service in IIS and the polling service in Windows Service.
Communication limitations is minimal between the two services and no need for events.
Test each service interdependently through their interfaces.
Low coupling and high cohesion between the services (this is what we want!).
Cons:
More services means more interfaces and contracts to maintain.
Higher complexity.

Related

Should I Open and Close my WCF client after each service call?

I have developed a WCF service for consumption within the organization's Ethernet.
The service is currently hosted on a windows-service and is using net.tcp binding.
There are 2 operation contracts defined in the service.
The client connecting to this service is a long running windows desktop application.
Employees(>30,000) usually have this client running throughout the week from Monday morning to Friday evening straight.
During this lifetime there might be a number of calls to the wcf service in question depending on a certain user action on the main desktop client.
Let us just say 1 in every 3 actions on the main desktop application would
trigger a call to our service.
Now we are planning to deploy this window service on each employee's desktop
I am also using `autofac` as the dependency resolver container.
My WCF service instance context is `PerSession`, but ideally speaking we have both the client and service running in the same desktop (for now) so I am planning to inject the same service instance for each new session using `autofac` container.
Now am not changing the `InstanceContext` attribute on the service implementation
because in future I might deploy the same service in a different hosting environment where I would like to have a new service object instance for each session.
Like mentioned earlier the client is a long running desktop application and I have read that it is a good practise to `Open` and `Close` the proxy for each call but if I leave the service to be PerSession it will create a new service instance for each call, which might not be required given the service and client have a 1-1 mapping. Another argument is that I am planning to inject the same instance for each session in this environment, so Open & Close for each service call shouldn't matter ?
So which approach should I take, make the service `Singleton` and Open Close for each call or
Open the client-side proxy when the desktop application loads/first service call and then Close it only when the desktop application is closed ?
My WCF service instance context is PerSession, but ideally speaking we have both the client and service running in the same desktop (for now) so I am planning to inject the same service instance for each new session using autofac container
Generally you want to avoid sharing a WCF client proxy because if it faults it becomes difficult to push (or in your case reinject) a new WCF to those parts of the code sharing the proxy. It is better to create a proxy per actor.
Now am not changing the InstanceContext attribute on the service implementation because in future I might deploy the same service in a different hosting environment where I would like to have a new service object instance for each session
I think there may be some confusion here. The InstanceContext.PerSession means that a server instance is created per WCF client proxy. That means one service instance each time you new MyClientProxy() even if you share it with 10 other objects being injected with the proxy singleton. This is irrespective of how you host it.
Like mentioned earlier the client is a long running desktop application and I have read that it is a good practise to Open and Close the proxy for each call
Incorrect. For a PerSession service that is very expensive. There is measurable cost in establishing the link to the service not to mention the overhead of creating the factories. PerSession services are per-session for a reason, it implies that the service is to maintain state between calls. For example in my PerSession services, I like to establish an expensive DB connection in the constructor that can then be utilised very quickly in later service calls. Opening/closing in this example essentially means that a new service instance is created together with a new DB connection. Slow!
Plus sharing a client proxy that is injected elsewhere sort of defeats the purpose of an injected proxy anyway. Not to mention closing it in one thread will cause a potential fault in another thread. Again note that I dislike the idea of shared proxies.
Another argument is that I am planning to inject the same instance for each session in this environment, so Open & Close for each service call shouldn't matter ?
Yes, like I said if you are going to inject then you should not call open/close. Then again you should not share in a multi-threaded environment.
So which approach should I take
Follow these guidelines
Singleton? PerCall? PerSession? That entirely depends on the nature of your service. Does it share state between method calls? Make it PerSession otherwise you could use PerCall. Don't want to create a new service instance more than once and you want to optionally share globals/singletons between method calls? Make it a Singleton
Rather than inject a shared concrete instance of the WCF client proxy, instead inject a mechanism (a factory) that when called allows each recipient to create their own WCF client proxy when required.
Do not call open/close after each call, that will hurt performance regardless of service instance mode. Even if your service is essentially compute only, repeated open/close for each method call on a Singleton service is still slow due to the start-up costs of the client proxy
Dispose the client proxy ASAP when no longer required. PerSession service instances remain on the server eating up valuable resources throughout the lifetime of the client proxy or until timeout (whichever occurs sooner).
If your service is localmachine, then you consider the NetNamedPipeBinding for it runs in Kernel mode; does not use the Network Redirector and is faster than TCP. Later when you deploy a remote service, add the TCP binding
I recommend this awesome WCF tome

Failover mechanisum for WCF services serving enterprise application

We have set of WCF services running on single computer which collectively serves an WPF application which could be on same machine or on remote machine (within same network only). We need failover mechanisum so whenver any of the service crashes or hangs - we want to restart the service and initialize it by calling appropriate method.
Since we are not aware of what is the industry standard for implementing failover for WCF service - we have implemented like this way. We start main WCF service hosted in console app along with one more secondary WCF service which constantly checks health of main WCF service by calling exposed method on given endpoint. If main WCF service fails, it takes role of main WCF service and launches another secondary WCF service.
The above approach is working fine but only problem we have seen is memory since we launch services in pair and every host requires 10MB of memory.
Can anyone help me what is the industry practice for implementing failover for this kind of scenario?

wcf services for interprocess communication

I have put together a .net winform application which consumes a wcf service exposed by another .net application running as a windows service.
Since the communication is within the same machine, I chose the NetNamedPipe as the communication channel, as it is the best choice suited for inter process communication in the same machine.
I want to know if I am using the correct property choices when defining the wcf service in the .net windows service.
The WCF service behaviour is defined as:
[ServiceBehavior(
ConcurrencyMode = ConcurrencyMode.Single,
InstanceContextMode = InstanceContextMode.Single)]
I chose the "InstanceContextMode" as Single so that I know objects in the wcf service are not recreated each time a wcf service method is called by the UI client.
However, while reading up the ConcurrencyMode property to choose on MSDN, I did get a little confused. At the basic level, I understand the ConcurrencyMode property dictates whether the wcf service supports a single, multiple or reentrant calls.
Does this mean, that if my UI client application is multithreaded and I call into the wcf service methods from those threads, I should choose "Concurrency" mode as "multiple" and if my UI client is not multi threaded, I should choose "Concurrency" mode as "single"? My UI client application is not running multiple threads. All operations are performed on the main UI thread through event handlers (through button clicks, combo box selections, etc...)
I am having situations where, after installing the application on a windows test machine, my UI client is sometimes not able to connect to the wcf service. It just keeps waiting on the call to the Connect method of the wcf client object and then eventually times out. I want to know if its related to the "ConcurrencyMode" choice I made. Or is this a "NetNamedPipe" communication channel problem?
Please advice.
Thanks in advance.
Subbu
Choose concurency mode as multiple only if your host object is thread safe i.e you have manually implemented locking on shared resource or your host object dont have any shared or class level objects at all. If host object is not thread safe use concurency mode as single as in this case wcf will automatically implement lock for you, only one request will be processed at a time on a context, parallel will be queued. So here decision should really depend on if your host object is thread safe or not.

WCF Communication with Host

I am writing an application that has one Windows Service that needs to communicate with another Windows Service. The "target" service will accept a request from the "source" service and will perform a task. The "source" service will not wait for a response, so the request should return as soon as possible.
The plan was to have the "target" service host a WCF service which the "source" will communicate with. Once the request is received I need to communicate with the host Windows Service to tell it to do the work. I was thinking that the "target" WCF service would put a message on a MSMQ which the "target" Windows service will monitor. Once this is done the WCF service can return back to the caller.
Does this sound like a sensible approach for allowing a WCF service to tell a hosting Windows Service to perform a task?
Kind Regards
Michael
Allow me to disagree. Based simply on what you've described, using MSMQ to communicate between the "target" WCF service and the hosting Windows service seems extremely heavyweight to me. MSMQ allows different processes to communicate in a failsafe manner. In your case, the WCF service is hosted in the same process as the Windows service. Thus, while MSMQ as a commmunication mechanism between the two would work, it's not necessary.
Additionally, using the MSMQ binding between the "target" WCF service and the "source" WCF service makes sense if the two WCF services are not always running at the same time. For example, if the "target" WCF service is not always running, the MSMQ binding would allow the "source" WCF service to still send tasks. These tasks would be stored in the MSMQ to be retrieved when the "target" WCF service begins running. However, it sounds like both services will be running, so I can't see the need for the MSMQ binding.
For selecting WCF bindings, refer to this SO post.
C# - WCF - inter-process communication
Let me address one other thing. When your "target" WCF service receives a task request from the "source," simply communicating the task back to the Windows service is not going to do anything in and of itself. The Windows service is running, yes, but it does not have a thread of execution that you can leverage. The point is that in order to make task processing asynchronous, you'll need to start a thread to manage the task(s). I would suggest leveraging the ThreadPool to do this.
Hope this helps.
Yeah, that is a good approach. MSMQ is perfect for this task - the source service can send a request to the target by putting a message on the queue via WCF. MSMQ is good anytime you want to send a request to a service for asynchronous processing, especially if you don't need to get a response back. If you do need a response, you can setup the source as a WCF service as well, and the target can send a message back if needed. There are several different ways to accomplish this with the MSMQ binding.
#Matt
Thanks for your help.
After thinking about it a bit more and see how your approach would make things easier to setup and use. I need to have the "target" service send the outcome of the work back to the "source", so I will probably use nettcp and use a callback. The plan then is to setup a new thread, do the work and once its finished send a response back to the "source".
#Andy
Thanks for you help.
I took a look at msmq, but seeing as I would probably have to setup a new thread once I receive the message I might as well let the web service do the work.

WCF Service worker thread communicate with ServiceHost thread

I have a windows NT Service that opens a ServiceHost object. The service host context is per-session so for each client a new worker thread is created. What I am trying to do is have each worker thread make calls to the thread that started the service host.
The NT Service needs to open a VPN connection and poll information from a device on the remote network. The information is stored in a SQL database for the worker threads to read. I only want to poll the device if there is a client connected, which will reduce network trafic. I would like the worker threads to tell the service host thread that they are requesting information and start the polling and updating the database. Everything is working if the device is alway being polled and the database being updated.
Why not implement singleton and init this property after service creation. After that you can always refer to it.
private static MyService m_ServiceInstance;
public static MyService ServiceInstance
{
get { return m_ServiceInstance; }
}
I suggest turning the code that opens a VPN connection and polls for information into its own singleton service and hosting it withing the same (or different) Windows NT Service. The client facing service calls the VPN service using WCF. The VPN service would only poll when client facing services are "listening".
This has a couple advantages:
WCF will take care of the complexities of creating service instances and managing threads. (Within the singleton you will likely still have to implement locking, but that's all.)
The VPN polling service is no longer tightly coupled to the client facing service. This gives you flexibility in deployment and the ability to support new use cases in the future.