I have created a WCF service and have its operationcontract and implementation like this:
[OperationContract]
Task<string> GetName(string name);
public async Task<string> GetName(string name)
{
await Task.Delay(5000);
var task1 = Task<string>.Factory.StartNew(() =>
{
return "Your name is : " + name;
});
var result = await task1;
return result;
}
Now i am using this service at client side and created the client.
ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
It shows be 2 methods for my implementation: GetName and GetNameAsync
I can use the following two ways to access the service.
var result_GetName = await Task.Factory.StartNew(() => client.GetName("My Input"));
var result_GetNameAsync = await client.GetNameAsync("My Input");
Please guide.
I don't know what the generated code looks like for WCF, but I'd expect the second form to be better. (EDIT: Read Stephen's blog post for details of why this is true.)
The first approach creates a new task which calls the method synchronously - blocking a thread for as long as it takes for the method to return. So if you have lots of those calls concurrently, you'll end up using a lot of threads and therefore memory.
I'd expect the second approach to be more "natively" asynchronous - basically sending the request and then handling the response on a potentially different thread when it comes back.
For your final question:
For the second call i am using async-await at two places (clien-server), is there any advantage of it?
You're using await in two places in both snippets. But yes, there's definitely an advantage in using asynchronous code in both places. In the client, you're saving client threads. In the server, you're saving server threads.
Using the purely asynchronous version, you could have hundreds of calls from a client to a server, without using more than one or two threads in each of those processes. In the client, you don't have anything blocked, waiting for the response - you just have continuations ready to be called when the response comes through. In the server, you don't have anything blocked on a Thread.Sleep call (the logical synchronous equivalent of Task.Delay) - you just have a lot of continuations ready to run when the delay expires.
So yes, it's good on each side. You get the benefit wherever you're using it, basically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With