第21章 线程

使用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.");
        }
    }
}
2789632-7ef4b8e83dfc4589.png

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相对速度要快一些。不知道这样比较是片面的,以后还要多多留意。


2789632-6180f3885cfae701.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值