C# 多線程批量數據處理

1.應用場景分析:假設有一組已知數量的數據,按照一定的業務處理規則處理並保存數據庫,如何提升數據處理的效率並完成數據保存(具體情況具體分析)?此處使用控制檯方式模擬輸入數據(類比保存數據庫處理)。

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApi
{
    /// <summary>
    /// 多線程批量數據處理
    /// </summary>
    public class MultithreadBatchDataProcessing
    {
        //線程安全隊列
        private ConcurrentQueue<ResponseModel> queue = new ConcurrentQueue<ResponseModel>();

        /// <summary>
        /// 模擬設置數據
        /// </summary>
        public void SetData()
        {
            Console.WriteLine($"開始數據設置,時間:{DateTime.Now};");
            for (int i = 0; i < 10000; i++)
            {
                var model = new ResponseModel { Code=i, Msg=$"第{i+1}次循環", Data=$"產生隨機數:{new Random().Next(1000,10000)}" };
                queue.Enqueue(model); //模擬數據入隊
                Thread.Sleep(1);    //這裏是隨機數生成時需要
            }
            Console.WriteLine($"10000條數據設置完畢!時間:{DateTime.Now};");
        }

        /// <summary>
        /// 多線程處理數據
        /// </summary>
        public void MultitDataProcessing()
        {
            int threadCount = 10; //開啓10個線程
            for (int i = 0; i < threadCount; i++)
            {
                string fileName = $"task{i}.txt";
                //開啓新線程
                Task.Factory.StartNew(() =>
                {
                    var sb = new StringBuilder();
                    int j = 0;
                    //數據循環出隊
                    while (queue.TryDequeue(out ResponseModel model))
                    {
                        //處理數據
                        if (model != null)
                            sb.AppendLine($"==》Code={model.Code},Msg={model.Msg},Data={model.Data}");

                        if (j % 100 == 0 || (queue.Count.Equals(0) && j < 100))
                        {   
                            Console.WriteLine($"每100條輸出一次控制檯,並暫停100毫秒, 第{i}次文件:{fileName}");
                            Console.WriteLine(sb.ToString());
                            sb = new StringBuilder();
                            Thread.Sleep(100);
                        }
                        j++;
                    }
                });
            }
        }
    }
}

2. 模擬10000條數據批量處理,每100條數據保存一次,調用顯示如下:

var mbdp = new MultithreadBatchDataProcessing();
mbdp.SetData();
mbdp.MultitDataProcessing();

C# 多線程批量數據處理演示Demo完畢。保存數據庫時可以創建DataTable採用SqlBulkCopy每100條推入一次即可;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章