Friday, July 6, 2012

Async WCF Service

1. Service Contracts

[ServiceContract]
public interface ITestService
{

[OperationContract(AsyncPattern = true)]
IAsyncResult BeginCallTestProcedure(int i,AsyncCallback asyncCallback, Object state);


int EndCallTestProcedure(IAsyncResult result);
}

2. Service Implementation:

public class TestService:ITestService
{
public IAsyncResult BeginCallTestProcedure(int i, AsyncCallback asyncCallback, object state)
{
Func invokeOperation=(x) => new ProcedureWorker().CallTestProcedure(x);
return invokeOperation.BeginInvoke(i, asyncCallback, state);
}


public int EndCallTestProcedure(IAsyncResult iAsyncResult)
{
var asynResult = (System.Runtime.Remoting.Messaging.AsyncResult)iAsyncResult;
var func = (Func)asynResult.AsyncDelegate;
return func.EndInvoke(iAsyncResult);
}
}


public class ProcedureWorker
{
public int CallTestProcedure(int i)
{
for (int j = 0; j < 3; j++)
{
Console.WriteLine(j);
Thread.Sleep(1000);
}
return i+1;
}
}

3. Client Side Invoke:

var wcfClient=....
var result= wcfClient.BeginCallTestProcedure(3,null,null);
Console.WriteLine(wcfClient.EndCallTestProcedure(result));

No comments: