C# 异步 Thread

注意:含参的线程,参数必须是object类型

含参的线程,可以把数据从主线程传到子线程

一、线程

1、创建

a、创建Thread实例,并传入 ThreadStart 委托,可以配置是否为后台线程

b、调用Thread.Start 方法,还可以传参

2、终止

a、调用Thread.Join 方法,等待线程结束

b、调用Thread.Interrupt 方法,中断执行的线程,注意(如果线程包含while true循环,需要IO,或其他阻塞方法)

二、案例

1、开启线程,等待线程结束

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

namespace ConsoleApp
{
    internal class Program
    {
        static void Main(string[] args)
        {   
            // 创建线程对象
            Thread thread = new Thread(ThreadMethod);
            // 
            thread.IsBackground = true;
            // 开启线程
            thread.Start();
            Console.WriteLine("主线程,等待线程结束");
            // 等待线程结束
            thread.Join();
            Console.WriteLine("Done");
        }
        static void ThreadMethod() 
        {
            for (int i = 0; i < 20; i++)
            {
                Thread.Sleep(200);
                Console.WriteLine("Thread is still running..");
            }
        }
    }
}

2、开启线程,中断线程

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

namespace ConsoleApp
{
    internal class Program
    {
        static void Main(string[] args)
        {   
            // 创建线程对象
            Thread thread = new Thread(ThreadMethod);
            // 
            thread.IsBackground = true;
            // 开启线程
            thread.Start();
            Console.WriteLine("主线程,等待线程结束");
            // 2秒后,中断线程
            Thread.Sleep(2000);
            thread.Interrupt();
            Console.WriteLine("Done");
        }

        static void ThreadMethod() 
        {
            for (int i = 0; i < 20; i++)
            {
                Thread.Sleep(200);
                Console.WriteLine("Thread is still running..");
            }
        }
    }
}

 

posted @ 2025-06-15 21:04  市丸银  阅读(11)  评论(0)    收藏  举报