4.0用 Task.Factory.StartNew(()=>{});
4.0以下用 ThreadPool.QueueUserWorkItem(()=>{})
4.0以上用 Task.Run(()=>{});
多任务:
Task[] tasks = new Task[maxCurrent];
for (int i = beginId; i <= maxId; i += interval, counter++)
tasks[counter] = new Task(worker.TestHandler, TaskCreationOptions.LongRunning);
var continuation = Task.Factory.ContinueWhenAll(
tasks,(antecedents) =>{
LogInfo("All threads have loaded!");
});
foreach (Task t in tasks)
t.Start();
LogInfo("All threads have been queued. Waiting to complete...");
while (!continuation.IsCompleted)
Thread.Sleep(1000);
static Random _random = new Random();
static void Main(string[] args)
{
ArrayList listThread = new ArrayList();
ArrayList listResult = new ArrayList();
for (int i = 0; i < 10; i++)
{
Thread thread = new Thread(new ParameterizedThreadStart(WorkThread));
thread.Start(listResult);
listThread.Add(thread);
}
foreach (Thread thread in listThread)
{
thread.Join();
}
foreach (int i in listResult)
{
Console.WriteLine(i);
}
}
static void WorkThread(object list)
{
int cnt = _random.Next(1,10);
ArrayList listLocal = new ArrayList();
for (int i = 0; i < cnt; i++)
{
listLocal.Add(cnt);
Thread.Sleep(100);
}
lock (list)
{
(list as ArrayList).AddRange(listLocal);
}
}