码迷,mamicode.com
首页 > 编程语言 > 详细

C#多线程の遇见长耗时操作以及多任务

时间:2017-09-13 20:17:39      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:tin   pool   hand   star   running   static   val   join   ext   

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

C#多线程の遇见长耗时操作以及多任务

标签:tin   pool   hand   star   running   static   val   join   ext   

原文地址:http://www.cnblogs.com/xietianjiao/p/7517361.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!