WCF实例与并发
实例模式 :
{
PerSession,
PerCall,
Single
}
并发部分:
{
Single,
Reentrant,
Multiple
}
public interface IAdd
{
[OperationContract]
void Add(int x, int y);
}
{
private readonly int counter = 0;
public AddService()
{
counter++;
Console.ResetColor();
Console.WriteLine(string.Format("AddService Construction function excute... counter is {0}", counter));
}
#region IAdd 成员
public void Add(int x, int y)
{
var clientId = OperationContext.Current.IncomingMessageHeaders.GetHeader<int>(MessageWrapper.headerClientId,
MessageWrapper.headerNamespace);
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(string.Format("Time:{0};ThreadId is :{1}.Request Id is {2} Add Method Invoked,", DateTime.Now,Thread.CurrentThread.ManagedThreadId,clientId));
Console.WriteLine(string.Format("result is : {0}",x + y));
Thread.Sleep(5000);
Console.WriteLine("=========Excute finished=========");
Console.WriteLine();
}
#endregion
}
<services>
<service name="Service.AddService">
<endpoint address="http://127.0.0.1:3636/AddService" binding="basicHttpBinding" contract="Contract.IAdd"></endpoint>
</service>
</services>
</system.serviceModel>
客户端配置这里不再给出。 客户端调用代码:
for (int i = 0; i < 5; i++)
{
ThreadPool.QueueUserWorkItem(delegate
{
int clientId = Interlocked.Increment(ref index);
using (OperationContextScope contextScope =
new OperationContextScope(proxy as IContextChannel))
{
MessageHeader<int> header = new MessageHeader<int>(clientId);
System.ServiceModel.Channels.MessageHeader messageHeader =
header.GetUntypedHeader(MessageWrapper.headerClientId,
MessageWrapper.headerNamespace);
OperationContext.Current.OutgoingMessageHeaders.Add(messageHeader);
proxy.Add(1, 2);
}
});
}
测试1:PreCall + Multiple:
输出如下:
图1
由以上输出,服务对客户端调用是以串行的方式进行的。 以上我们设置的ConcurrencyMode.Muliple。明明是并发模式,为何服务端却以串行的方式执行呢。?这是因为如果服务代理以自动开启的方式(即进行调用时,如果代理没有打开,调用时会打开代理)进行并发调用,WCF需要对调用进行序列化知道代理打开之后在进行并发处理。如果将代理显示开启,则就能显示并发调用结果。对代码进行如下修改:
if (null != proxy as ICommunicationObject)
{
(proxy as ICommunicationObject).Open();
}
for ()
{
/**/ }
服务端输出如下:
图2
测试2:PerSession + Single/Reentrant
测试3: Single + Single
图3
测试4: Single + Multiple
测试5:PerCall+ Single/Reentrant/Multiple
图5
由以上分析对于不同实例模式,以及并发模式总结如下图: