Calling WCF in async manner from client makes the WCF service also act in async manner? - wcf

When a WCF service is called in an async manner from a client, then we know that the client app is NOT blocked.
But is the thread on the WCF side blocked while executing the async method call OR the WCF releases the thread it uses to initiate the method call ?
For example, if I call the 'Add' method in an async manner from an ASP.Net app, as in code below, will the service instance in back-end wait till method completes? The WCF uses an InstanceContext of PerCall.
CalculatorClient client = new CalculatorClient();
// AddAsync
double value1 = 100.00D;
double value2 = 15.99D;
client.AddCompleted += new EventHandler<AddCompletedEventArgs>(AddCallback);
client.AddAsync(value1, value2);

WCF support for asynchronous calls are strictly a client-side feature only.
In-fact the service has no way (and should not have) of telling the difference between two clients, one making a synchronous call and the other making an asynchronous call.
This is true regardless of whether the client is making a call via an async proxy, or directly via async invocation.
It is easy to show this is true with a thought experiment; ANY wcf service can be called asynchronously, and additionally this is REGARDLESS of the binding selected - therefore this must be solely a client-side facility.

Related

WCF Asynch pattern - Really required?

I have created one WCF service which performs a lengthy operation asynchronously using Asynch pattern. I have referred to below link to implement BeginAddNumbers and EndAddNumbers methods in the ServiceContract.
http://aspalliance.com/1335_Asynchronous_Pattern_in_Windows_Communication_Foundation.5
Everything is working fine. But I dont understand why we require this approach?
Even though its asynchronous operation on server, client will still blocked and we
have to invoke this operation asynchornously on client as well.
So instead of implementing operation asynchronously on server it's always
better to invoke operation asynchronously on client side to have responsive UI.
Can anyone help me to understand concept of implementing asynchronous operation on server side? Any practical example where I need to play around AsyncPattern=true in conjunction with OperationContract ?
Adding client code. Client is implemented using WPF application
private void button1_Click(object sender, RoutedEventArgs e)
{
MathOperationClient c = new MathOperationClient();
Task t = new Task(new Action(() =>
{
///Even if AddNumbers is is implemented as asynchronous operation
///second call to AddNumbers get chance only after completing below
///call.
///Note: AddNumbers method takes 10 sec to execute
int nResult = c.AddNumbers(2, 3);
this.Dispatcher.BeginInvoke(new Action(()=>{
label1.Content = nResult.ToString();
})
, null);
}));
t.Start();
Task t1 = new Task(new Action(() =>
{
///Below method is invoked only after executing first call ( above call with parameters 2 and 3 )
///in other words below call is blocked for 10 seconds.
///So what is advantage of implementing asynchronous AddNumbers method on server side?
int result = c.AddNumbers(5,5);
this.Dispatcher.BeginInvoke(new Action(() =>
{
label2.Content = result.ToString();
})
, null);
}));
t1.Start();
}
Thanks, Hemant
this post has some information.
in general:
In case of WCF, the realproxy is of type System.ServiceModel.Channels.ServiceChannelProxy. This proxy implementation calls service method synchronously even if we call it using BeginInvoke.
WCF only issues asynchronous calls if the method that is called on a proxy begins with BeginXXX() and is decorated with [OperationContract(AsyncPattern=true)] attribute.
I like the idea to implement this server side; and clearly indicate this by naming the operation accordingly. After all, if a call is asynchronous in nature, why give the client the choice?
Another reason is scalability: doing it server-side decouples the request from the WCF dispatcher thread. This means that WCF threads will not be blocked.
See here for an example.
You could even decide to make it a one way call; and have the client poll at regular intervals; which is, in fact, my favorite approach.

wcf async callback

I have WCF service which sends messages to its clients. I would like to call callback methods asynchronously. I have read this answer:
WCF asynchronous callback
But there is one problem. When I am generating IMyServiceCallback from WebServiceReference it contains both synchronous and asynchronous methods (while on the service side there is callback contract with only asynchronous methods - BeginCallbackMethod and EndCallbackMethod). What is more when I call from MyService to calback BeginCallbackMethod, on the client side (in callback implementation) it is using synchronous CallbackMethod. The question is why? Is there any way to configure it?
By default WCF will call the synchronous version of an operation if both sync and async are present; I don't know how (or if) you can change that logic, but one thing you can do is to simply remove the synchronous method from the generated callback interface. The callback code should continue to work, and it will use the asynchronous implementation instead. You can also just remove the [OperationContract] attribute from the synchronous version, to the same effect.

Async WFC server side like IHttpAsyncHandler

I'd like to be able to create a WCF service that the client see as synchronous, but is implemented server side as asynchronous. I know that ASP.NET allows me to do this by implementing the IHttpAsyncHandler, but can't seem to find the equivalent in WCF.
This is a service that exists already and we'd like to move over to an asynchronous implement server side, without changing the client. Is this possible?
If you are on .Net 4.5 change the OperationContract methods in service contract interface to return Task<type> instead of type. In the class that implements the interface use the async modifier on the methods and use await inside following the Task based Asynchronous Pattern
See http://msdn.microsoft.com/en-us/library/ms734701
http://channel9.msdn.com/Events/TechEd/NorthAmerica/2012/DEV326

Force a client to call a method on the service?

I'm wondering if there's any way to force a client to call a specific method on a duplex WCF service. My situation is this, my service implementation is going to keep a collection of subscribers. The problem with this approach is, what if the client doesn't call Subscribe()? I was thinking that in my client interface, I'd have a method called Subscribe, but that doesn't get me anywhere since the code to actually call the service can still be left out of the implementation. Is this possible?
Thanks!
Duplex WCF service uses WCF session so you can mark your Subscribe method with:
[OperationContract(IsInitiating=true)]
void Subscribe();
All other methods will have IsInitiating=false and because of that Subscribe method will have to be the first method called to start a new session. You can also have special method with IsTerminating=true to close the session.

WCF client side instancing and concurrency issues

Hopefully WCF has a reach instancing and concurrency management at service-side via Throttling.
My service client is an ASP.NET application. It consumes more than one WCF service so I create and parametrize WCF client at run-time (no configuration file is used).
Only the end point address is dynamic, and all the services (used by client) have the same method signatures (same contract).
For this reason I have referenced the service through Visual Studio and it has created my service proxy so I just take care of endpoint address at run-time:
class MyWcfClient
{
void DoSomething(string endpintAddress, int data)
{
// Create 'binding' and 'endpoint' ('endpoint' address is dynamic)
ServiceReference.ServiceClient serviceClient = new ServiceReference.ServiceClient(binding, endpoint);
// Parametrize 'serviceClient'
// Call WCF method (send 'data' to appropriate endpoint)
serviceClient.CLose();
}
}
Since the client is an asp.net application, each request runs on it's own worker thread (WCF method calls are very light and fast, so the thread would not block for a long time).
My question is about the instanciation and concurrency at the client-side.
Should MyWcfClient class be Singleton with one serviceClient instance or it be static class and a new serviceClient be created for each call ?
Should I create serviceClient (i.e, an array or list) based on the endpoints (there are 10-100 endpoints) ?
Note that my asp.net threads should not be blocked for a long time (i.e waiting in a queue for sending their related data via WCF)
There is no throttling on client side and it is not needed because you have client code under your control so you have control over number of requests executed. That is the difference to service where without throttling there is no control over number of incomming requests executed elsewhere (out of service control).
So if you want to control number of requests concurrently executed on client you must create object pool - there will be only limited number of MyWcfClient classes available and each class will always create new ServiceClient. Requests will wait in queue for free MyWcfClient instance.
If your only problem is how to create instances of ServiceClient then answer depends on type of binding.
Sessionful bindings like Net.Tcp, Net.Pipe or WsHttp with reliable session or security context: Create new instance for each communication relation. If your relation is just single call, create new instnace for each call. So you can use static class with static method and create new instance in that method.
Sessionless bindings like BasicHttp or WebHttp: You can reuse client for multiple calls but you can't close the client between subsequent calls. You can use array of prepared client instances. You will still need to handle some errors here.
Btw. also check asynchronous client calls and how to correctly close the service client.