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

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

转载于:https://www.cnblogs.com/xietianjiao/p/7517361.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值