C#中线程的建立、挂起、继续与销毁

在c#中,对于不需要考虑严格时序的任务,线程是一个很方便的东西。
将没一个单独需要执行的事情都作为一个线程,在主函数中调用就可以了。

新建一个项目之后,需要引入线程相关的命名空间,里面包含了线程相关class的定义、功能函数等内容。

using System.Threading;

先定义一个thread类型的变量,其中th是该线程的名字,如果需要对该线程进行操作,就是对变量th的操作;ThreadMethod则是该线程所执行的函数。

Thread th = new Thread(ThreadMethod); //创建线程    

线程函数内容如下,该函数是每隔500ms像控制台打印一次东西。

static void ThreadMethod()
        {
            while (true)
            {
                Console.Write("thread\r\n");
                Thread.Sleep(500);
            }
        }

一边用到线程的情况都是一个线程一直监听并处理一些事情,所以会有一个while(true),即永不退出。
由于线程和主进程一样,是一直在执行并且常驻内存的,(一般的子函数都是在堆栈中运行,调用的时候就在堆栈中临时租借一块地,函数执行完了再把那块地儿还给你。而static关键字就是说,系统啊你要给我在内存里专门开一块儿地方放置我的代码块,我以后可是你的固定客户),所以线程函数也和主函数一样,需要加static关键字,并且是 void 类型的。
当线程需要启动时(假设你这个线程是统计景区人流量的,作为主管的你在家睡大觉,然后请一个零时工过来干货):

th.Start(); //启动线程

当线程需要挂起时(现在你亲戚来了你给她开个后门直接放进去,这个时候就暂时不需要统计了),执行Suspend函数可以实现线程的挂起:

th.Suspend();//挂起线程

当线程需要继续开始时(亲戚都进去玩了),执行Resume函数可以实现线程的继续运行:

th.Resume();//继续线程

当线程需要停止时(下班了),执行Abort函数可以实现线程的中止:

th.Abort();//中止线程

整体代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace test
{
    class Program
    {
        static void ThreadMethod()
        {
            while (true)
            {
                Console.Write("thread\r\n");
                Thread.Sleep(500);
            }
        }
        static void Main(string[] args)
        {
            Console.Write("main start\r\n");
            Thread th = new Thread(ThreadMethod); //创建线程                     
            th.Start(); //启动线程
            for (int i = 0; i < 10; i++)
            {
                if (i == 3) th.Suspend();
                if (i == 5) th.Resume();
                if (i == 7) th.Abort();
                //if (i == 9) th.Resume();  /*异常:已引发: "线程目前未运行;无法使其继续。*/
                Console.Write(i + "\r\n");
                Thread.Sleep(1000);
            }
            Console.Write("main end\r\n");
            Console.ReadKey();
        }
    }
}

运行效果如下图:
在这里插入图片描述

 

出处:https://blog.csdn.net/qq_27508477/article/details/87177332

posted on 2020-12-28 16:39  jack_Meng  阅读(6478)  评论(0编辑  收藏  举报

导航