还在苦苦敲代码开发APP?你out啦! 试试积木搭建APP吧~

WCF:使用Array替代List

来源:清泛编译     2015-11-02 15:11:38    人气:     我有话说( 0 人参与)

本文主要介绍WCF中arrays 及 generic lists的区别。

英文原文:http://www.codeproject.com/Articles/45298/Array-instead-of-List-in-WCF

最近我正在开发一个在消息报文中传输image的函数,因此习惯性地在消息类中建立了一个类似这样的属性:public List<byte> Image { get; set; }

Image数据通过duplex channel传到客户端,你能想象我是多么惊讶地看到服务进程的CPU消耗吗?约400K的Image CPU达到了15-20%。我必须考虑一个更好的方案了。

以下是WCF中duplex channel的结构:
[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. 
    }
}

搜索这个问题的解决方案花了我相当数量的时间,然后以字节数组(array of bytes)替换List<byte>得到了更好的结果:CPU基本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倍,消息报文大小相同的情况下CPU消耗能够从15-20%降到1-3%。我很惊讶,因为关于这个差异我没有找到任何官方资料。

WCF Array List

注:本文为本站或本站会员原创优质内容,版权属于原作者及清泛网所有,
欢迎转载,转载时须注明版权并添加来源链接,谢谢合作! (编辑:admin)
分享到: