C#-线程-start

线程是轻量级进程。一个使用线程的常见实例是现代操作系统中并行编程的实现.

Thread.CurrentThread; 获取当前正在运行的线程。

 

static void Main(string[] args)
        {
            Thread th = Thread.CurrentThread;
            th.Name = "MainThread"; // 设置线程的名字
            Console.WriteLine("This is {0}", th.Name); // 获取线程的名字
            Console.ReadKey();
        }

  [Thread 类常用的属性和方法](https://www.runoob.com/csharp/csharp-multithreading.html)

创建线程

线程是通过扩展 Thread 类创建的。扩展的 Thread 类调用 Start() 方法来开始子线程的执行。

1
2
Thread childThread = new Thread(childref); // childref线程要执行的方法的名
childThread.Start();

  

1
2
3
4
5
ThreadStart childref = new ThreadStart(CallToChildThread); // ThreadStart ?
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();

  

管理线程

1
Thread.Sleep(5000); // 5000毫秒 = 5s<br>thread.join(); // 阻塞除了thread的线程,先让thread线程执行完,再执行其他的线程

  

销毁线程

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public static void CallToChildThread()
    {
        try
        {
 
            Console.WriteLine("Child thread starts");
            // 计数到 10
            for (int counter = 0; counter <= 10; counter++)
            {
                Thread.Sleep(500);
                Console.WriteLine(counter);
            }
            Console.WriteLine("Child Thread Completed");
 
        }
        catch (ThreadAbortException e) // 其他线程调用Abort()命令导致该线程被迫中断时,便会进入这里
        {
            Console.WriteLine("Thread Abort Exception");
        }
        finally
        {
            Console.WriteLine("Couldn't catch the Thread Exception");
        }
 
    }
    
    static void Main(string[] args)
    {
        ThreadStart childref = new ThreadStart(CallToChildThread);
        Console.WriteLine("In Main: Creating the Child thread");
        Thread childThread = new Thread(childref);
        childThread.Start();
        // 停止主线程一段时间
        Thread.Sleep(2000);
        // 现在中止子线程
        Console.WriteLine("In Main: Aborting the Child thread");
        childThread.Abort(); // 因主线程sleep开始的时间是子线程开始执行的时间;故子线程应该也执行了sleep的时间2000毫秒
        Console.ReadKey();
    }
}

  

posted @   木梓棋  阅读(109)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类
点击右上角即可分享
微信分享提示