天天看點

C# 線程池(ThreadPool)批量儲存資料執行完沒别的操作執行完有别的邏輯

執行完沒别的操作

效果圖

C# 線程池(ThreadPool)批量儲存資料執行完沒别的操作執行完有别的邏輯

實際代碼

實體類

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}
           

線程池傳遞的參數

public class ThreadPoolParamModel
{
    public ThreadPoolParamModel()
    {
        list = new List<Person>();
    }
    public List<Person> list { get; set; }
}
           

儲存資料邏輯

/// <summary>
/// 儲存資料
/// </summary>
/// <param name="param"></param>
private static void Save(object param)
{
    var model = (ThreadPoolParamModel)param;
    //寫下儲存的邏輯
    Console.WriteLine("儲存資料");
    Thread.Sleep(1000);
    Interlocked.Increment(ref pageIndex);
    if (pageIndex == pageCount)
    {
        Console.WriteLine("所有線程池執行結束");
        _event.Set();
    }
}
           

主要代碼(可以根據實際需求進行改動)

public static int pageIndex = 0;//某個線程池
public static int pageCount = 0;//最大線程池
public static ManualResetEvent _event = new ManualResetEvent(false);
public static void Main(string[] args)
{
    List<Person> list = new List<Person>();
    list.Add(new Person { Id = 1, Name = "張三", Age = 10 });
    list.Add(new Person { Id = 2, Name = "李四", Age = 20 });
    list.Add(new Person { Id = 3, Name = "王五", Age = 30 });
    int count = list.Count();//要儲存的所有記錄
    int pageSize = 2;//每次儲存的記錄
    pageCount = (count % pageSize) == 0 ? (pageSize / pageSize) : (pageSize / pageSize + 1);//計算可開的線程池數
    for (var i = 0; i < pageCount; i++)
    {
        ThreadPoolParamModel param = new ThreadPoolParamModel();
        param.list = list.Skip(pageSize * (i - 1)).Take(pageSize).ToList();//取出pageSize筆記錄
        ThreadPool.QueueUserWorkItem(new WaitCallback(Save), param);
    }
    Console.WriteLine("等待線程池完成操作......");
    _event.WaitOne(Timeout.Infinite, true);
    Console.WriteLine("程式執行完成");
    Console.ReadLine();
}
           

執行完有别的邏輯

效果圖

C# 線程池(ThreadPool)批量儲存資料執行完沒别的操作執行完有别的邏輯

實際代碼

實體類

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}
           

線程池傳遞的參數

public class ThreadPoolParamModel
{
    public ThreadPoolParamModel()
    {
        list = new List<Person>();
    }
    public List<Person> list { get; set; }
}
           

儲存資料邏輯

/// <summary>
/// 儲存資料
/// </summary>
/// <param name="param"></param>
private static void Save(object param)
{
    var model = (ThreadPoolParamModel)param;
    //寫下儲存的邏輯
    Console.WriteLine("儲存資料");
}
           

所有線程執行完成後執行的邏輯

/// <summary>
/// 所有線程執行完成後執行的邏輯
/// </summary>
/// <param name="str"></param>
private static void WriteStr(string str)
{
    Console.WriteLine(str);
}
           

主要代碼

public static void Main(string[] args)
{
    RegisteredWaitHandle rhw = null;

    List<Person> list = new List<Person>();
    list.Add(new Person { Id = 1, Name = "張三", Age = 10 });
    list.Add(new Person { Id = 2, Name = "李四", Age = 20 });
    list.Add(new Person { Id = 3, Name = "王五", Age = 30 });
    int count = list.Count();//要儲存的所有記錄
    new Action(() =>
    {
        int pageSize = 2;//每次儲存的記錄
        var pageCount = (count % pageSize) == 0 ? (pageSize / pageSize) : (pageSize / pageSize + 1);//計算可開的線程池數
        for (var i = 0; i < pageCount; i++)
        {
            new Action<int>((index) =>
            {
                ThreadPoolParamModel param = new ThreadPoolParamModel();
                param.list = list.Skip(pageSize * (index - 1)).Take(pageSize).ToList();//取出pageSize筆記錄
                ThreadPool.QueueUserWorkItem(new WaitCallback(Save), param);
            }).BeginInvoke(i, null, null);
        }
    }).BeginInvoke(null, null);
    rhw = ThreadPool.RegisterWaitForSingleObject(new AutoResetEvent(false), new WaitOrTimerCallback((obj, b) =>
    {
        int workerThreads = 0;
        int maxWordThreads = 0;
        int compleThreads = 0;
        ThreadPool.GetAvailableThreads(out workerThreads, out compleThreads);
        ThreadPool.GetMaxThreads(out maxWordThreads, out compleThreads);
        //當可用的線數與池程池最大的線程相等時表示線程池中所有的線程已經完成
        if (workerThreads == maxWordThreads)
        {
            rhw.Unregister(null);
            WriteStr("所有線程執行完成後執行的邏輯");
            rhw = null;
        }
    }), null, 100, false);
    Console.WriteLine("程式執行完成");
    Console.ReadLine();
}