C#基础知识学习之 ☀️ | 多线程的使用基础—管理线程和销毁线程

举报
呆呆敲代码的小Y 发表于 2021/10/29 17:05:45 2021/10/29
2.1k+ 0 0
【摘要】 管理线程Thread类提供了各种管理线程的方法。下面的实例演示了 sleep()方法的使用,用于在一个特定的时间暂停线程。 void Start() { ThreadStart childref = new ThreadStart(CallToChildThread); Debug.Log("In Main: Creating the Child t...

管理线程

Thread类提供了各种管理线程的方法。

下面的实例演示了 sleep()方法的使用,用于在一个特定的时间暂停线程。

    void Start()
    {
        ThreadStart childref = new ThreadStart(CallToChildThread);
        Debug.Log("In Main: Creating the Child thread");
        Thread childThread = new Thread(childref);
        childThread.Start();
    }

    public static void CallToChildThread()
    {
        Debug.Log("子线程开启");
        // 线程暂停 5000 毫秒
        int sleepfor = 5000;
        Debug.Log("子线程等待 "+sleepfor / 1000+ " 秒");
        Thread.Sleep(sleepfor);
        Debug.Log("子线程唤醒");
    }

打印结果:
在这里插入图片描述


销毁线程

Abort()方法用于销毁线程。

通过抛出threadabortexception在运行时中止线程。这个异常不能被捕获,如果有finally块,控制会被送至finally块。

下面的程序说明了这点:

 void Start()
    {
        ThreadStart childref = new ThreadStart(CallToChildThread);
        Debug.Log("In Main: Creating the Child thread");
        Thread childThread = new Thread(childref);
        childThread.Start();
        // 停止主线程一段时间
        Thread.Sleep(2000);
        // 现在中止子线程
        Debug.Log("In Main: Aborting the Child thread");
        childThread.Abort();
    }

    public static void CallToChildThread()
    {
        try
        {
            Debug.Log("子线程开始");
            // 计数到 10
            for (int counter = 0; counter <= 10; counter++)
            {
                Thread.Sleep(500);
                Debug.Log(counter);
            }
            Debug.Log("子线程完成");

        }
        catch (ThreadAbortException e)
        {
            Debug.Log("线程中止异常:" + e);
        }
        finally
        {
            Debug.Log("无法捕获线程异常");
        }
    }

打印结果:
在这里插入图片描述


总结

多线程还有很多使用技巧,本篇博客就作为一篇引子简单介绍一下多线程的基础用法,包括创建、暂停和销毁等

后面会进行更深入的研究,包括线程锁等等用法!

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

作者其他文章

评论(0

抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。