C# Task多线程与队列

  • A+
所属分类:.NET技术
摘要

public static void RunTask(List list, Action action, int threadCount = 5, bool waitFlag = true)
{
ConcurrentQueue queue = new ConcurrentQueue(list);
Task[] tasks = new Task[threadCount];
for (int i = 0; i < threadCount; i++)
{
tasks[i] = Task.Run(() =>
{
T t;
while (queue.TryDequeue(out t))
{
action(t);
}
});
}
if (waitFlag)
{
Task.WaitAll(tasks);
}
}
//调用方法
new System.Threading.Thread(delegate()
{
IP.RunTask(list, _num =>
{
List_int.Dispatcher.Invoke(delegate()
{
List_int.Items.Add(_num + DateTime.Now.ToString(“YYYY-MM-dd-mm-ss”));

public static void RunTask(List list, Action action, int threadCount = 5, bool waitFlag = true)
{
ConcurrentQueue queue = new ConcurrentQueue(list);
Task[] tasks = new Task[threadCount];
for (int i = 0; i < threadCount; i++)
{
tasks[i] = Task.Run(() =>
{
T t;
while (queue.TryDequeue(out t))
{
action(t);
}
});
}
if (waitFlag)
{
Task.WaitAll(tasks);
}
}
//调用方法
new System.Threading.Thread(delegate()
{
IP.RunTask(list, _num =>
{
List_int.Dispatcher.Invoke(delegate()
{
List_int.Items.Add(_num + DateTime.Now.ToString("YYYY-MM-dd-mm-ss"));

                });                 //MessageBox.Show();                 System.Threading.Thread.Sleep(2000);                 List_int.Dispatcher.Invoke(delegate()                 {                     List_int.Items.Add("结束" + _num);                 });             });             MessageBox.Show("结束");         }            ).Start();