wraith
wraith

Reputation: 351

how to call wcf service asynchronously from MVC4's controller

I created a project that have WCF service and client consume it asynchronously

(like the one in http://msdn.microsoft.com/en-us/library/bb885132.aspx)

The problem comes with me if the client is MVC4

When I call the wcf from client-side, the code is

      ChannelFactory<IMathService> myChannelFactory = 
     new ChannelFactory<IMathService>(myBinding, myEndpoint);

        myChannelFactory.Open();
        IMathService instance = myChannelFactory.CreateChannel();
        // Call Service.

        IAsyncResult ar = instance.BeginFunction(param,
            (are) =>
            {
                result = ((IMathService)are.AsyncState).EndFunction(are);
            }
            , instance);

        return View(result);

With this code, my "result" is always default value.

How can I make the action wait until the result has value from EndFunction?

Thanks

Upvotes: 2

Views: 1112

Answers (1)

Maxim
Maxim

Reputation: 7348

You need to use ASP .NET MVC AsyncController

Full explanation - http://msdn.microsoft.com/en-us/library/ee728598(v=vs.98).aspx

Edited sample for your scenario-

public class PortalController : AsyncController {
public void NewsAsync(string city) {

    AsyncManager.OutstandingOperations.Increment();


          ChannelFactory<IMathService> myChannelFactory = 
 new ChannelFactory<IMathService>(myBinding, myEndpoint);

    myChannelFactory.Open();
    IMathService instance = myChannelFactory.CreateChannel();
    // Call Service.

    IAsyncResult ar = instance.BeginFunction(param,
        (are) =>
        {
            AsyncManager.Parameters["result"] = ((IMathService)are.AsyncState).EndFunction(are);
            AsyncManager.OutstandingOperations.Decrement();
        }
        , instance);
}

public ActionResult NewsCompleted(string[] result) {
    return View(result);
}

}

Upvotes: 2

Related Questions