C#多线程の遇见长耗时操作以及多任务(简明记要)

时间:2021-09-24 20:24:31

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);
}
}