Xamarin 异常 - 合同包含不支持的同步操作

Xamarin exception - The contract contains synchronous operations, which are not supported

我遇到了非常奇怪的异常:

An exception of type 'System.InvalidOperationException' occurred in System.ServiceModel.ni.dll but was not handled in user code

Additional information: The contract 'ICalculatorService' contains synchronous operations, which are not supported in Silverlight. Split the operations into "Begin" and "End" parts and set the AsyncPattern property on the OperationContractAttribute to 'true'. Note that you do not have to make the same change on the server.

我有世界上最简单的 WCF 服务。没有异步代码。就是这样:

主持人:

[ServiceContract]
public interface ICalculatorService
{
    [OperationContract]
    string GetSum(int a, int b);
}

public class CalculatorService : ICalculatorService
{
    public string GetSum(int a, int b)
    {
        return (a + b).ToString();
    }
}

class Program
{
    static void Main(string[] args)
    {
        Uri[] addressBase = new Uri[] { new Uri("http://localhost:9003/CalculatorService") };
        var host = new ServiceHost(typeof(CalculatorService), addressBase);
        host.Open();
        Console.Read();
    }
}

主机配置:

<system.serviceModel>
  <services>
    <service name="MobileWCF.ServerHost.CalculatorService">
      <endpoint address="net.tcp://localhost:8003/CalculatorService" binding="netTcpBinding"
        contract="MobileWCF.Contracts.ICalculatorService" />
      <endpoint address="http://localhost:9003/CalculatorService" binding="basicHttpBinding"
        contract="MobileWCF.Contracts.ICalculatorService" />
    </service>
  </services>
</system.serviceModel>

然后,我添加了 Xamarin.Forms(便携式)项目,添加了视图,并在 onClickEvent 的代码隐藏中添加了:

    void OnButtonClicked(object sender, EventArgs e)
    {
        string strAddress = "http://localhost:9003/CalculatorService";
        BasicHttpBinding httpBinding = new BasicHttpBinding();
        EndpointAddress address = new EndpointAddress(strAddress);

        ChannelFactory<ICalculatorService> channel = new ChannelFactory<ICalculatorService>(httpBinding, address);
        var game = channel.CreateChannel(address);
        var num = game.GetSum(3,4);
    }

为什么我会收到此异常。 Xamarin.Forms 不允许同步服务吗? 一切都应该在 Begin/End APM 模型中吗?

Xamarin 说:

Xamarin.Forms has full support for the Windows Phone 8.1 platform using WinRT. The look and feel of apps using Windows Phone 8.1 support may be different to your earlier Xamarin.Forms Windows Phone apps that were based on Silverlight.

Silverlight 中的所有服务调用都是异步的。 为此用途:

[OperationContract(AsyncPattern = true)]

有关详细信息,请参阅:here

好的,让我们看看。您正在使用 Xamarin.Forms 和 PCL 项目。 PCL 项目使用与 Silverlight 相同的配置文件,而 Silverlight 不支持同步方法,因此您的应用不支持它们。

如果您想使用它,或更改方法以遵循异步模式或更改您的项目类型以使用共享项目,则共享项目不使用可移植 class 配置文件,可以使用完整框架。