第21章 线程

作者: 张中华 | 来源:发表于2017-10-26 00:10 被阅读37次

    使用Thread类可以创建和控制线程。

    基础应用

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace Threading
    {
        class Program
        {
            static void Main(string[] args)
            {
                var t1 = new Thread(ThreadMain);
                t1.Start();
                Console.WriteLine("This is the main thread.");
                Task.Run(() => { Console.WriteLine("Runing in the second thread."); });
                Console.ReadLine();
            }
            static void ThreadMain()
            {
                Console.WriteLine("Runing in a thread.");
            }
        }
    }
    

    task与thread的异同(答案收集于百度):

    task是根据自己需要调用线程,thread就是个基本单位;
    thread是单核多线程,task是多核多线程;
    直接用Thread做多线程和 用Task目前还是看不出太大的区别;
    Task对象需要更多的内存,但任务运行的更快;
    从网上百度了一个比较task,thread,threadpool效率的代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace Threading
    {
        static class Program
        {
            static void Main(string[] args)
            {
                for (var i = 1; i <= 50; i++)
                    TestTask(i);
                for (var i = 1; i <= 50; i++)
                    TestThreadPool(i);
                for (var i = 1; i <= 50; i++)
                    TestThread(i);
                Console.ReadLine();
            }
    
            private static void TestThread(int i)
            {
                Console.WriteLine("Thread {0} start.", i);
                new Thread(h =>
                {
                    Thread.Sleep(5000);
                    Console.WriteLine("-------------------Thread {0} end.", i);
                }).Start();
            }
    
            private static void TestThreadPool(int i)
            {
                Console.WriteLine("ThreadPool {0} start.", i);
                ThreadPool.QueueUserWorkItem(h =>
                {
                    Thread.Sleep(5000);
                    Console.WriteLine("-------------------ThreadPool {0} end.", i);
                });
            }
    
            private static void TestTask(int i)
            {
                Console.WriteLine("Task {0} start.", i);
                new Task(() =>
                {
                    Thread.Sleep(5000);
                    Console.WriteLine("-------------------Task {0} end.", i);
                }).Start();
            }
        }
    }
    
    

    由下图可见,thread相对速度要快一些。不知道这样比较是片面的,以后还要多多留意。


    相关文章

      网友评论

        本文标题:第21章 线程

        本文链接:https://www.haomeiwen.com/subject/jmxhpxtx.html