WCF主机和客户端处于同一进程时的TimeoutException

时间:2011-01-02 19:29:39

标签: wcf nettcpbinding timeoutexception

我遇到了一个非常奇怪的问题。我正在构建一个分布很广的应用程序,其中每个应用程序实例可以是WCF服务的主机和/或客户端(非常像p2p)。一切正常,只要客户端和目标主机(我指的是应用程序,而不是主机,因为目前一切都在一台计算机上运行(所以没有防火墙问题等))不一样。 如果它们是相同的,那么应用程序挂起正好1分钟,然后抛出TimeoutException。 WCF-Logging没有产生任何帮助。 这是一个小应用程序,它演示了问题:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        var binding = new NetTcpBinding();
        var baseAddress = new Uri(@"net.tcp://localhost:4000/Test");

        ServiceHost host = new ServiceHost(typeof(TestService), baseAddress);
        host.AddServiceEndpoint(typeof(ITestService), binding, baseAddress);

        var debug = host.Description.Behaviors.Find<ServiceDebugBehavior>();
        if (debug == null)
            host.Description.Behaviors.Add(new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true });
        else
            debug.IncludeExceptionDetailInFaults = true;

        host.Open();

        var clientBinding = new NetTcpBinding();
        var testProxy = new TestProxy(clientBinding, new EndpointAddress(baseAddress));
        testProxy.Test();
    }
}

[ServiceContract]
public interface ITestService
{
    [OperationContract]
    void Test();
}

public class TestService : ITestService
{
    public void Test()
    {
        MessageBox.Show("foo");
    }
}

public class TestProxy : ClientBase<ITestService>, ITestService
{
    public TestProxy(NetTcpBinding binding, EndpointAddress remoteAddress) :
        base(binding, remoteAddress) { }

    public void Test()
    {
        Channel.Test();
    }
}

我做错了什么?

此致 Pharao2k

1 个答案:

答案 0 :(得分:5)

你把所有东西放在同一个线程中。您不能在同一个线程上拥有客户端和服务器,至少不能在此类代码中使用。

如果您这样做,例如:

    ThreadPool.QueueUserWorkItem(state =>
    {
        var clientBinding = new NetTcpBinding();
        var testProxy = new TestProxy(clientBinding, new EndpointAddress(baseAddress));
        testProxy.Test();
    });

您的代码应该更好。

PS:即使在同一台机器上你也可能遇到防火墙问题 - 好吧,这是一个功能,而不是问题: - )。

相关问题