C#中使用ProtoBuf将list进行序列化并保存到文件

场景

C#中使用ProtoBuf提高序列化速度对比二进制序列化:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/99850052

实现

参考上面那篇博客,进而将序列化后的数据写入文件。

新建Winforn程序,然后拖拽两个Button。

第一个Button用来构建一个1000长度的list对象。

先声明一个全局的list变量。

List<Request> requestList = new List<Request>();

然后在第一个按钮点击事件中

  

 private void button4_Click(object sender, EventArgs e)
        {
            DateTime begin = DateTime.Now;
            Console.WriteLine("protobuf初始化数据开始" + begin.ToString("yyyy-MM-dd HH:mm:ss"));
            for (int i = 1; i <= 1000; i++)
            {
                requestList.Add(new Request() { id = i,password = "密码"+i});
            }
            DateTime end = DateTime.Now;
            TimeSpan ts = end - begin;
            Console.WriteLine("protobuf初始化数据结束" + end.ToString("yyyy-MM-dd HH:mm:ss"));
            Console.WriteLine("共花费" + ts.TotalSeconds);
        }

注:

这里的类文件是根据.prpto文件生成的,所以其初始化赋值方式注意要如上使用。

然后在第二个按钮的点击事件中:

 

 private void button6_Click(object sender, EventArgs e)
        {
            DateTime begin = DateTime.Now;
            Console.WriteLine("ProtoBuf保存数据开始" + begin.ToString("yyyy-MM-dd HH:mm:ss"));
            using (System.IO.FileStream fs = new System.IO.FileStream(@"E:\testdata1\Record2.data", System.IO.FileMode.Create, System.IO.FileAccess.Write))
            {
                ProtoBuf.Serializer.Serialize(fs, this.requestList);
            }
            DateTime end = DateTime.Now;
            TimeSpan ts = end - begin;
            Console.WriteLine("ProtoBuf保存数据结束" + end.ToString("yyyy-MM-dd HH:mm:ss"));
            Console.WriteLine("花费时间" + ts.TotalSeconds);
        }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霸道流氓气质

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值