C#多线程之ManualResetEvent,Thread,ThreadPool,BackgroudWoker

ManualResetEvent基本概念:

创建对象的构造函数参数说明

ManualResetEvent(bool arg),true表示有信号状态,false表示无信号状态

set将该对象设置为有信号,如果一个线程调用该对象的waitOne方法,会继续往下执行,不会被阻塞。

reset将该对象设置为无信号,如果一个线程调用该对象的waitOne方法,会被阻塞。

AutoResetEvent和ManualResetEvent的不同之处在于,waitOne通过之后,自动设置为无信号状态。

Thread参数

不考虑栈大小,Thread构造函数类型是2个委托类型

比如对于

public static void ParaProc(object  para)
        {
            Console.WriteLine("In this thread,I just wrote a line with arg  "+para);
        }

创建Thread对象有两种方法,创建委托对象或者直接传入方法名

Thread th1 = new Thread(new ParameterizedThreadStart(ParaProc));
Thread th2 = new Thread(ParaProc);

ParameterizedThreadStart和ThreadStart区别在于,前者th.Start加个参数.

线程池

其中WaitCallback是委托,

对于上述的ParaProc方法,使用线程池可以这样调用

ThreadPool.QueueUserWorkItem(ParaProc),或者价格参数ThreadPool.QueueUserWorkItem(ParaProc,3),

当然如此简短的方法可以使用lambda表达式

ThreadPool.QueueUserWorkItem(x =>
            {
                Console.WriteLine("yesyes");
            });
原文地址:https://www.cnblogs.com/legion/p/9104973.html