tags:

views:

14

answers:

1

I am creating a WCF service, and it is timing out when it is used in some of my integration tests. I have been able to narrow it down and it is demonstrated by the following code. It appears that creating a Form before you create the host causes the problem, but I'm not sure why.

class Program
{
    [ServiceContract]
    public interface IMyContract
    {
        [OperationContract]
        void Ping();
    }
    public class MyContract : IMyContract
    {
        public void Ping()
        {
            Console.WriteLine("Ping");
        }
    }
    public class MyContractProxy : ClientBase<IMyContract>, IMyContract
    {
        public MyContractProxy(int port)
            : base(new NetTcpBinding { SendTimeout = TimeSpan.FromSeconds(5) }, new EndpointAddress(string.Format("net.tcp://localhost:{0}", port)))
        {
        }

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

    static void Main(string[] args)
    {
        try
        {
            new Form();
            var host = new ServiceHost(typeof(MyContract));
            host.AddServiceEndpoint(typeof(IMyContract), new NetTcpBinding(), "net.tcp://localhost:12345");
            host.Open();

            var proxy = new MyContractProxy(12345);
            proxy.Open();
            proxy.Ping();
        }
        catch (Exception e)
        {
            Console.Error.WriteLine(e);
        }
    }
}
+1  A: 

The Form changes behavior of your service - your proxy and service runs in the same thread.

There is difference in hosting service in UI thread and non UI thread. When you host the service in non UI thread, service create new thread for handling the request. If you host the service in UI thread (it happens if you run any WinForm or WPF form there) it does not use new threads by default. Instead it process incomming calls as part of standard windows message loop.

Add ServiceBehavior to avoid this behavior:

[ServiceBehavior(UseSynchronizationContext=false)]
public class MyContract : IMyContract
{ ... }
Ladislav Mrnka
That is exactly the problem. Thanks!
Brian Kohrs