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

Pha*_*o2k 1 wcf timeoutexception nettcpbinding

我遇到了一个非常奇怪的问题.我正在构建一个分布很广的应用程序,其中每个应用程序实例可以是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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

此致,Pharao2k

Sim*_*ier 5

你把所有东西放在同一个线程中.您不能在同一个线程上拥有客户端和服务器,至少不能在这种代码中.

如果你改为这样做,例如:

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

你的代码应该更好.

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