如何从MVC4的控制器异步调用wcf服务

时间:2014-06-04 06:52:22

标签: wcf asp.net-mvc-4 asynchronous

我创建了一个具有WCF服务的项目,客户端异步使用它

(就像http://msdn.microsoft.com/en-us/library/bb885132.aspx中的那个)

如果客户端是MVC4

,问题就出现了

当我从客户端调用wcf时,代码是

      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);

使用此代码,我的“结果”始终是默认值。

如何使操作等到结果具有EndFunction的值?

由于

1 个答案:

答案 0 :(得分:2)

您需要使用ASP .NET MVC AsyncController

完整解释 - http://msdn.microsoft.com/en-us/library/ee728598(v=vs.98).aspx

针对您的方案编辑过的示例 -

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);
}

}