• 关于Task类处理多线程简单示例


    1.定义一个线程
    var task1 = Task.Factory.StartNew(() => DoSomeWork());
    方法如下:
      View Code
            private static object DoSomeWork()
            {
                Console.WriteLine("nihao ");
                System.Threading.Thread.Sleep(3000);
                Console.Write("nihao ");
                return "xiexie";
            }

    2.多线程执行后,执行另一个方法
      var task1 = Task.Factory.StartNew(() => DoSomeWork()).ContinueWith(
                     task => { Console.WriteLine(task.Result.ToString()); }).ContinueWith(
                     task => { Console.WriteLine(task.Result.ToString()); });
    3.等待所有线程结束
    var task1 = Task.Factory.StartNew(() => DoSomeWork());
    var task2 = Task.Factory.StartNew(() => DoSomeWork());
    var task3 = Task.Factory.StartNew(() => DoSomeWork());
    Task.WaitAll(task1, task2, task3);
    4.等待其中一个线程结束
    var task1 = Task.Factory.StartNew(() => DoSomeWork());
    var task2 = Task.Factory.StartNew(() => DoSomeWork());
    var task3 = Task.Factory.StartNew(() => DoSomeWork());
    Task.WaitAny(task1, task2, task3);
    5.等待所有线程结束执行的方法
    var task1 = Task.Factory.StartNew(() =>
    {
        Thread.Sleep(3000);
        return "dummy value 1";
    });
    var task2 = Task.Factory.StartNew(() =>
    {
        Thread.Sleep(3000);
        return "dummy value 2";
    });
    var task3 = Task.Factory.StartNew(() =>
    {
        Thread.Sleep(3000);
        return "dummy value 3";
    });
    Task.Factory.ContinueWhenAll(new[] { task1, task2, task3 }, tasks =>
    {
        foreach (Task<string> task in tasks)
        {
            Console.WriteLine(task.Result);
        }
    });

  • 相关阅读:
    window.parent ,window.top,window.self 详解及parent和opener的区别
    jQuery $.extend()用法总结
    JQuery中each()的使用方法说明
    jQuery.isPlainObject()的作用
    change和onchange、click和onclick的区别
    zabbix客户端一键安装脚本(主动模式监控)
    jumpserver在centos 7上的部署
    用阿里云的免费 SSL 证书让网站从 HTTP 换成 HTTPS
    GitLab的安装及使用教程
    一个客户端一键安装环境和服务的shell脚本
  • 原文地址:https://www.cnblogs.com/fuchongjundream/p/4054573.html
Copyright © 2020-2023  润新知