开发者

TimeoutException when WCF Host and Client are in the same process

开发者 https://www.devze.com 2023-02-02 06:45 出处:网络
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 fin

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.IncludeExceptionDetailInFaul开发者_StackOverflowts = 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


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 :-).

0

精彩评论

暂无评论...
验证码 换一张
取 消