Domanda

I work on WCF. It should have sync and async implementation The main constraint is non-blocking async version I have implemented this part of the interface:

[OperationContract]
[FaultContract(typeof(FaultException))]
int Method1(string userName, string companyName);

now I should implement the async part of the interface:

//Is it correct interface

[OperationContract]
[FaultContract(typeof(FaultException))]
Task<int> Method1Async(string userName, string companyName);
//int Method1Async(string userName, string companyName);

Is it correct and good for performance to do the following:

Task<int> myTask = new Task<string>(() => Method1(userName,companyName));
myTask.Start();
int res = await myTask;
return myTask;//return res;
È stato utile?

Soluzione

No, it is not good performance at all. Your client side code does not need to know if the server side is sync or async.

Instead just leave your code as Method1 and on the client code just have the client code generate both synchronous and asynchronous functions.

Via SvcUtil.exe

svcutil.exe /async /lang:csharp http://YourWcfUrlHere.com

Via GUI: enter image description here

This will create int Method1(string userName, string companyName); and Task<int> Method1Async(string userName, string companyName); client side even though only int Method1(string userName, string companyName); exists server side.

Altri suggerimenti

You have two ways of implementing your Task based return.

//Not as good, uses more marshaling than really needed.
Task<int> Method1Async(string userName, string companyName)
{
    return Task.Run(() => Method1(username, companyName));
}

OR

Task<int> Method1Async(string userName, string companyName)
{
    return Task.Result(Method1(username, companyName));
}

Notice I haven't used the word async once.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top