双工WCF通信在Metro应用程序中不起作用

时间:2012-02-21 02:07:38

标签: c# .net wcf microsoft-metro

您能否告诉我为什么与TcpTransportBindingElement的双工通信在我的Metro应用程序中不起作用?

根据 this 文档.Net Framework的Metro子集支持TCP绑定。

所以我写了WCF服务器作为控制台应用程序。这是源代码:

static void Main()
{
    UiWcfSession.OnInitialize += ClientInitialize;

    var baseAddresses = new Uri("net.tcp://localhost:9000/");

    var host = new ServiceHost(typeof(UiWcfSession), baseAddresses);

    var reliableSession = new ReliableSessionBindingElement { Ordered = true, InactivityTimeout = TimeSpan.MaxValue };
    var binding =
        new CustomBinding(reliableSession, new TcpTransportBindingElement()) { ReceiveTimeout = TimeSpan.MaxValue };

    host.AddServiceEndpoint(typeof(IClientFulfillmentPipeService), binding, "");

    var metadataBehavior = new ServiceMetadataBehavior();
    host.Description.Behaviors.Add(metadataBehavior);
    var mexBinding = MetadataExchangeBindings.CreateMexTcpBinding();
    host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, "mex");

    host.Open();

    Thread.CurrentThread.Join();
}

private static void ClientInitialize(int uiprocessid, string key)
{
    Debug.WriteLine("ClientInitialize");
}

以下是Metro app中的客户端代码:

partial class MainPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    private void onclick(object sender, RoutedEventArgs e)
    {
        try
        {
            var ep = new EndpointAddress("net.tcp://localhost:9000/");
            var binding = new CustomBinding(new TcpTransportBindingElement());
            var ctx = new InstanceContext(new Wrapper());
            var pipeFactory = new DuplexChannelFactory<IClientFulfillmentPipeService>(ctx, binding, ep);
            IClientFulfillmentPipeService commChannel = pipeFactory.CreateChannel();

            // open up the the comm channel with a reasonable timeout...
            ((IChannel)commChannel).Open();

            commChannel.Initialize(1234, "Test");

            ((IChannel)commChannel).Close();
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
    }
}

所以有点有效。但是当我在Metro应用程序中的调试器中一步一步地走时,它会挂起并且永远不会从函数commChannel.Initialize返回。

为什么会这样?我错过了什么?

1 个答案:

答案 0 :(得分:0)

原来我不能在Metro中使用同步客户端。我必须使用异步调用。这就是为什么它不起作用。