如何解决WCF传递大数据的问题

2025-04-23 11:32:36
推荐回答(1个)
回答(1):

使用WCF的默认DataContractSerializer手动去序列化成byte[],然后接收后再手动去反序列化,能解决这个问题。也就是说单纯的byte[]能过去,直接将下面代码中的list以List返回去就是出现LZ遇到的问题。

也就是说序列化与反序列化这一大块数据都没问题。主要问题还是出现在WCF组装消息上了。
设置一下 ReaderQuotas 这个属性,这是设置消息复杂性的。
感觉这种症状很像被DOS干掉的感觉,于是想到ReaderQuotas。

下面是我尝试的例子。
C# code
publicbyte[] GetMays() { DataContractSerializer DCZ =newDataContractSerializer(typeof(List)); List list =new List(); for (int i =0; i <30000; i++) { May tmp =new May { Name =DateTime.Now.ToString("yyyy-MM-dd") }; list.Add(tmp); } using(MemoryStream fs =new MemoryStream()) { DCZ.WriteObject(fs, list);return fs.ToArray(); } }
-------------------

用你这个方法搞定。客户端还要设置下
netTcpBinding.ReaderQuotas.MaxArrayLength = 2147483647;
netTcpBinding.ReaderQuotas.MaxStringContentLength = 2147483647;
netTcpBinding.ReaderQuotas.MaxBytesPerRead = 2147483647;

//-------------------------------
System.Diagnostics.Stopwatch myWatch = new System.Diagnostics.Stopwatch();
myWatch.Start();
// TaxiInfo[] taxiInfos = PositionService.GetAllTaxiInfos();
byte[] sds = PositionService.GetMays();
myWatch.Stop();
Console.WriteLine("耗时:" + myWatch.ElapsedMilliseconds + "ms");

MemoryStream memory = new MemoryStream(sds);
XmlDictionaryReader reader =
XmlDictionaryReader.CreateTextReader(memory, new XmlDictionaryReaderQuotas());
DataContractSerializer ser = new DataContractSerializer(typeof(List));
// Deserialize the data and read it from the instance.
List deserializedPerson =
(List)ser.ReadObject(reader, true);
reader.Close();
// Console.WriteLine(deserializedPerson);

这样就没问题了。