Parallel.ForEach , ThreadPool.QueueUserWorkItem

时间:2023-03-08 16:18:30
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace ParallelThreadPool
{
class Program
{
static void Main(string[] args)
{
List<int> list = InitialList();
Console.WriteLine("ParallelList开始");
ParallelList(list);
Console.WriteLine("ThreadPoolList开始");
ThreadPoolList(list);
Console.ReadKey();
} /// <summary>
/// 初始化队列
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
private static List<int> InitialList(int length)
{
List<int> list = new List<int>();
for (int i = ; i < length; i++)
{
list.Add(i);
}
return list;
} /// <summary>
/// Paralle循环
/// </summary>
/// <param name="list"></param>
private static void ParallelList(List<int> list)
{
Parallel.ForEach(list, (item) =>
{
Console.WriteLine(string.Format("Paralle循环,元素{0}", item));
});
Console.WriteLine("-----------------------------------Paralle----------------------------------");
} /// <summary>
/// ThreadPool循环
/// </summary>
/// <param name="list"></param>
private static void ThreadPoolList(List<int> list)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
{
foreach (var item in list)
{
Console.WriteLine(string.Format("ThreadPool循环,元素{0}", item));
}
}));
Console.WriteLine("-----------------------------------ThreadPool----------------------------------");
}
}
}

Parallel.ForEach , ThreadPool.QueueUserWorkItem

Parallel.ForEach:执行foreach操作,其中可能会并行迭代。

ThreadPool.QueueUserWorkItem:将方法排入队列以便执行。 此方法在有线程池线程变得可用时执行。

仅作为自己记录一下,验证猜想:

Parallel.ForEach不异步,并行迭代,执行顺序会乱。

ThreadPool.QueueUserWorkItem 开线程,异步不影响后面代码执行,按照队列顺序一个个执行。