WCF服务不兼容

时间:2013-08-06 17:34:09

标签: wcf

我有一个服务代码,如:

 [ServiceContract]
public interface IService1
{
    [OperationContract]
    void MyOperation1();
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession,ConcurrencyMode=ConcurrencyMode.Multiple)]
public class service1 : IService1
{
    public service1()
    {
        Console.WriteLine("creating instance");
    }
    public void MyOperation1()
    {
        Console.WriteLine("starting..");
        Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);
        Thread.Sleep(1000);
        Console.WriteLine("Ending..");
    }
}

我的客户端代码如下:

static void Main(string[] args)
    {
        Thread[] t = new Thread[10];
        NetTcpBinding myBinding = new NetTcpBinding();
        EndpointAddress myEndpoint = new EndpointAddress("net.tcp://localhost:8000/MyService");
        ChannelFactory<IService1> myChannelFactory = new ChannelFactory<IService1>(myBinding, myEndpoint);
        IService1 instance = myChannelFactory.CreateChannel();
        for (int i = 0; i < 10; i++)
        {
            t[i] = new Thread(new ThreadStart(delegate() 
            {
                instance.MyOperation1();
            }));
        }
        for (int i = 0; i < 10; i++)
        {
            t[i].Start();
        }          
    }

我得到一个输出(调用是逐个执行的):

creating instance
starting..
3
Ending..
starting..
3
Ending..
starting..
12
Ending..
starting..
3
Ending..
starting..
12
Ending..
starting..
3
Ending..
starting..
12
Ending..
starting..
3
Ending..
starting..
12
Ending..
starting..
3
Ending..

我期待所有的呼叫都像这样并行启动:

creating instance
starting..
starting..
starting..
starting..
3
Ending..
4
6
Ending..

1 个答案:

答案 0 :(得分:4)

这可能是由于您使用单个客户端(通道)实例。

您创建的新线程必须等待前一个线程释放该通道才能使用它。