我读了很多关于wcf并发和实例上下文模式的文章,我也阅读了CodeProject的文章,但仍然无法使其工作。这是我的客户端代码(如果你问我为什么使用实例上下文,那是因为我最终会测试回调函数,但是我还没有,只是尝试多次同时执行一个简单的请求/响应)WCF ConcurrencyMode多个不能正常工作
public void Run()
{
InstanceContext context = new InstanceContext(this);
MyServiceReference.MyService service = new MyServiceReference.MyService(context);
for (int i = 0; i < 10; i++)
{
int j = i;
Thread t = new Thread(() => myFun((j + 1), service));
t.Start();
}
countdownEvent.Wait();
Console.ReadLine();
service.Close();
}
private void myFun(int threadNo, MyServiceReference.MyServiceClient service)
{
Console.WriteLine(service.GetData1(threadNo));
countdownEvent.Signal();
}
这是该服务的代码:
[ServiceContract(CallbackContract = typeof(IMyServiceCallback))]
public interface IMyService
{
[OperationContract]
string GetData1(int value);
}
public interface IMyServiceCallback
{
[OperationContract]
string GetData2(int value);
}
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, UseSynchronizationContext=false)]
public class MyService : IMyService
{
public string GetData1(int value)
{
reponse = DateTime.Now.ToString();
Thread.Sleep(5000);
return "Request: " + value + ", Thread id: " + Thread.CurrentThread.ManagedThreadId + ", response: " + reponse;
}
这是输出:
Request: 1, Thread id: 9, response: 2015-08-14 11:39:42
Request: 2, Thread id: 10, response: 2015-08-14 11:39:47
Request: 3, Thread id: 8, response: 2015-08-14 11:39:52
Request: 4, Thread id: 9, response: 2015-08-14 11:39:57
Request: 5, Thread id: 10, response: 2015-08-14 11:40:02
Request: 6, Thread id: 9, response: 2015-08-14 11:40:07
Request: 7, Thread id: 10, response: 2015-08-14 11:40:12
Request: 8, Thread id: 9, response: 2015-08-14 11:40:17
Request: 9, Thread id: 10, response: 2015-08-14 11:40:22
Request: 10, Thread id: 9, response: 2015-08-14 11:40:27
我期望将ConcurrencyMode设置为多个会使请求通过使用多个线程同时运行,但即使我看到3个线程使用,操作仍然按顺序执行(每个响应之间5秒),我错过了什么?
我看到的每个例子都是使用void return和IsOneWay = True的操作,这就是为什么它不适合我吗? 但是,我在每个请求的客户端上使用不同的线程,因此即使每个线程都在等待自己的响应,所有请求都应该同时完成。
我在WCF服务主机和NetTcpBinding调试运行,可以运行在调试影响并发?
我认为这可能是由于使用相同的服务客户。默认情况下会话已启用,因此它可能只是作为同一会话的一部分依次执行它们。你可以尝试把SessionMode.NotAllowed放在你的服务行为上吗? – Juan
SessionMode在ServiceContract属性上不行为,但无论如何,似乎我无法关闭与netTcpBinding的会话。 为什么同一个客户端会话无法完成同时请求? – Jonathan
我尝试过使用许多不同的客户端,它按预期工作(请求同时执行),但如果我想使用同一个客户端呢?不可能? – Jonathan