C# Task多線程與隊列

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"));
spa

});
                //MessageBox.Show();
                System.Threading.Thread.Sleep(2000);
                List_int.Dispatcher.Invoke(delegate()
                {
                    List_int.Items.Add("結束" + _num);
                });
            });
            MessageBox.Show("結束");
        }
           ).Start();
相關文章
相關標籤/搜索