zoukankan      html  css  js  c++  java
  • 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);
    }
    }

  • 相关阅读:
    有关类成员变量和局部成员变量初始值设置问题
    Redis在windows下安装与配置
    java内存区域-方法区
    Java中的反射机制(一)
    (转)Spring实现IoC的多种方式
    UUID
    Python os.path
    Leetcode 215、数组中第k个最大的元素
    树的非递归遍历
    About MySQL
  • 原文地址:https://www.cnblogs.com/xietianjiao/p/7517361.html
Copyright © 2011-2022 走看看