C#中线程的使用(1)--Thread与ThreadPool

一、简介

简单记录一下c#中多线程的使用方法,在使用之前时候要弄明白几个问题,什么是进程?什么是线程?进程与线程之间是什么关系?

简单来说,一个运行的程序就是一个进程,一个进程可以包含多个线程,每个线程都是一个执行流,都拥有独立的寄存器和共享的代码存储区。

下面就来记录一下Thread与ThreadPool 的使用方法。

二、Thread的使用

2.1 使用Thread 开启一个线程 无参数传入

public static void Main()
{
    //方式1
      Thread thread1 = new Thread(new ThreadStart(SayHello));
    thread1.Start();
    
    //方式2 
    Thread thread2 = new Thread(() =>
    {
        Console.WriteLine("hello ");
    });
    thread2.Start();
}
private void SayHello()
{
    Console.WriteLine("hello");
}

2.2  传递参数到线程中

Thread thread = new Thread(Say);
thread.Start("Hello");//启动线程

//方法声明
private static void Say(object obj)
{
    Console.WriteLine(obj);
}

2.3 当我们想要等待线程结束后再执行后面程序时,可以使用Join

thread.Join();//等待线程 直到结束
thread.Join(1000); // 等待线程 1s钟   1000 是指等待的时间

2.4 通过Thread 封装一个可以注册回调函数的方法,实现计算结果的通知

Func<int, int> threadStart = (num) =>
{
    int sum = 0;
    for (int i = 0; i < num; i++)
    {
    sum += i;
    }
    return sum;
};
                 
Action<int> action = (sum) =>
{
    Console.WriteLine(sum);
};
this.ThreadContinueWith(threadStart, action);

//封装方法
private void ThreadContinueWith(Func<int,int> threadStart, Action<int> actionCallback)
{
    ThreadStart threadStart1 = new ThreadStart(() =>
    {
        int sum = threadStart.Invoke(10000);
        actionCallback.Invoke(sum);
    });
    Thread thread = new Thread(threadStart1);
    thread.Start();
}

2.5 Thread其他的操作

thread.IsBackground = true;//进程结束,线程也结束
thread.Abort();//终结线程
thread.Suspend();// 暂停线程,已弃用
thread.Resume();//恢复线程 ,已弃用

三、线程池ThreadPool的使用

3.1 使用线城池开启线程

//将方法排入队列以便执行 使用线程池执行方法 o为传递的参数,未传递参数时,o=null
ThreadPool.QueueUserWorkItem(o =>
{
    for (int i = 0; i < 10; i++)
    {
        Thread.Sleep(500); 
        Console.WriteLine(i);
    }
});
//传递参数
ThreadPool.QueueUserWorkItem(o =>
{
    for (int i = 0; i < (int)o; i++)
    {
        Thread.Sleep(500); 
        Console.WriteLine($"{i},{o}");
    }
},10);

3.2 线程池可以设置最大的线程数量

ThreadPool.SetMaxThreads(100, 100); //线程池中辅助线程的最大数目100,线程池中异步 I/O 线程的最大数目100  更改成功则会返回true
ThreadPool.SetMinThreads(12, 12);

3.3 可以使用ManualResetEvent来控制线程的开关

//ManualResetEvent 如果为 true,则将初始状态设置为终止;如果为 false,则将初始状态设置为非终止。
ManualResetEvent manualResetEvent = new ManualResetEvent(true); //开关关闭 
ThreadPool.QueueUserWorkItem(o =>
{
    Thread.Sleep(3000);
    manualResetEvent.Set();// 开关打开
});
manualResetEvent.WaitOne();//等待信号
Console.WriteLine("线程已结束");

 

posted @ 2022-11-14 20:11  just--like  阅读(161)  评论(0编辑  收藏  举报