Search code examples
wcfnettcpbindingtimeoutexception

TimeoutException when WCF Host and Client are in the same process


I've ran into a really weird problem. I am building a heavily distributed application where each app instance can either be a Host and/or Client to a WCF-Service (very p2p-like). Everything works fine, as long as the Client and the targeted Host (By which I mean the app, not the Host, since currently everything runs on a single computer (so no Firewall problems etc.)) are NOT the same. IF they are the same, then the app hangs for exactly 1 Minute and then throws a TimeoutException. WCF-Logging did not produce anything helpful. Here is a small app which demonstrates the Problem:

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

What am I doing wrong?

Regards, Pharao2k


Solution

  • You put everything in the same thread. You can't have a client and a server on the same thread, at least not in this kind of code.

    If you do this instead, for example:

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

    your code should work better.

    PS: even on the same machine you can have firewall problems - well, that's a feature, not a problem :-).