WCF 中的数组而非列表






4.71/5 (6投票s)
本文描述了在 WCF 中使用数组和泛型列表之间的差异。
引言
最近,我正在开发一个函数,其中包括在一个消息包中传输图像。因此,按照习惯,我在消息类中创建了一个如下属性:public List<byte> Image { get; set; }
。这个 Image
通过双工通道发送到客户端。你能想象我看到该服务进程的处理器占用率时有多惊讶吗?它被加载了大约 15-20%,图像大小约为 400 KB。然后我开始思考更好的解决方案。
背景
这是 WCF 中双工通道的结构
[ServiceContract(CallbackContract = typeof(IServiceCallback),
SessionMode = SessionMode.Required)]
public interface IService
{
[OperationContract(IsOneWay = true)]
void SendData(List<byte> array);
}
public interface IServiceCallback
{
[OperationContract(IsOneWay = true)]
void RecieveData(List<byte> array); //this is duplex receiver of image
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession,
ConcurrencyMode = ConcurrencyMode.Multiple,
MaxItemsInObjectGraph = Int32.MaxValue)]
public class Service : IService
{
public void SendData(List<byte> array)
{
IServiceCallback callback =
OperationContext.Current.GetCallbackChannel<IServiceCallback>();
callback.RecieveData(array);
//Receiving of message back to user.
//It is simple exaple is only to show high duplex performance.
}
}
Using the Code
寻找解决方案花费了我相当多的时间,然后,将类型 List<byte>
替换为字节数组后,我获得了明显更好的结果:实际上加载量约为 1-2%。为什么看似相同的数据类型之间会有如此大的差异? 差异在于 SOAP 消息的生成方式。对于 List<byte>
...
<s:Body u:Id="_0"
xmlns:u="http://docs.oasis-open.org/wss/2004/01/
oasis-200401-wss-wssecurity-utility-1.0.xsd">
<SendData xmlns="http://tempuri.org/">
<array
xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:unsignedByte>0</a:unsignedByte>
<a:unsignedByte>0</a:unsignedByte>
<a:unsignedByte>0</a:unsignedByte>
<a:unsignedByte>0</a:unsignedByte>
<a:unsignedByte>0</a:unsignedByte>
<a:unsignedByte>0</a:unsignedByte>
<a:unsignedByte>0</a:unsignedByte>
<a:unsignedByte>0</a:unsignedByte>
<a:unsignedByte>0</a:unsignedByte>
<a:unsignedByte>0</a:unsignedByte>
<a:unsignedByte>0</a:unsignedByte>
<a:unsignedByte>0</a:unsignedByte>
...
</array>
</SendData>
</s:Body>
...
对于字节数组
...
<s:Body u:Id="_0"
xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<SendData xmlns="http://tempuri.org/">
<array>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</array>
</SendData>
</s:Body>
...
关注点
通常,这两个 SOAP 消息的大小差异大约是 10 倍,并且在相同包大小的情况下,处理器的负载从大约 15-20% 降至大约 1-3%。我非常惊讶,因为我没有在任何地方找到关于这些差异的官方信息。