一方面,它试图把RemotingFormat设置为SerializationFormat.Binary来序列化DataSet; 另一方面,你也可以简单的把那行代码注释起来,并且让它保持默认值SerializationFormat.xml。在这种情况下,该例子都是通过计算执行deserialize这样一个DataSet操作所需要的时间来做大致的性能估计。如代码清单所示:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data;
using System.Runtime.Serialization.Formatters.Binary;
namespace Business
{
class DataSetSerialize
{
public void DataSetSerialization()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = new FileStream(System.Environment.CurrentDirectory.ToString() + "\\ds.dat", FileMode.OpenOrCreate);
DataSet ds = GiveMeFakeData();
ds.RemotingFormat = SerializationFormat.Binary;
bf.Serialize(fs, ds);
fs.Close();
// Check the deserialization performance.
fs = new FileStream(System.Environment.CurrentDirectory.ToString() + "\\ds.dat", FileMode.Open);
long nowTicks = DateTime.Now.Ticks;
DataSet ds2 = (DataSet)bf.Deserialize(fs);
long tickstotal = DateTime.Now.Ticks - nowTicks;
Console.WriteLine("Took me:" + tickstotal);
fs.Close();
}
}
}
因此,首先把RemotingFormat设置为SerializtionFormat.Binary运行这个例子,输出结果如下:using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data;
using System.Runtime.Serialization.Formatters.Binary;
namespace Business
{
class DataSetSerialize
{
public void DataSetSerialization()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = new FileStream(System.Environment.CurrentDirectory.ToString() + "\\ds.dat", FileMode.OpenOrCreate);
DataSet ds = GiveMeFakeData();
ds.RemotingFormat = SerializationFormat.Binary;
bf.Serialize(fs, ds);
fs.Close();
// Check the deserialization performance.
fs = new FileStream(System.Environment.CurrentDirectory.ToString() + "\\ds.dat", FileMode.Open);
long nowTicks = DateTime.Now.Ticks;
DataSet ds2 = (DataSet)bf.Deserialize(fs);
long tickstotal = DateTime.Now.Ticks - nowTicks;
Console.WriteLine("Took me:" + tickstotal);
fs.Close();
}
}
}
Took me:300432 ticks
接着,把RemotingFormat设置为SerializationFormat.xml运行这个例子,输出结果如下:
Took me:1201728 ticks
我们看使用Binary实现的真正的二进制序列化只有XML序列化的1/10那么大。
RemotingFormat属性值默认为Serializationformat.xm,这是为了向后兼容ADO.NET1.1。