public static void RunTask<T>(List<T> list, Action<T> action, int threadCount = 5, bool waitFlag = true)
{
ConcurrentQueue<T> queue = new ConcurrentQueue<T>(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();