Part 92 Significance of Thread Join and Thread IsAlive functions

本文详细解析了C#中Thread.Join与Thread.IsAlive的使用方法。Thread.Join使主线程等待被调用线程完成,可指定超时时间;Thread.IsAlive判断线程是否正在执行。通过示例代码展示了如何结合这两个方法进行线程管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Thread.Join & Thread.IsAlive functions

Join blocks the current thread and makes it wait until the thread on which Join method is invoked completes.Join method also has a overload where we can specify the timeout. If we don't specify the timeout the calling thread waits indefinitely(无限期地), until the thread on which Join() is invoked completes. This overloaded Join(int millisecondesTimeout) method returns boolean. True if the thread has terminated(终止) otherwise false.

Join is particularly(特别地) useful when we need to wait and collect result from a thread execution or if we need to do some clean-up after the thread has completed.

IsAlive returns boolean. True if the thread is still executing otherwise false.

public static void Main(string[] args)
        {
            Console.WriteLine("main start");
            Thread t1 = new Thread(ThreadFunction1);
            t1.Start();
            Thread t2 = new Thread(ThreadFunction2);
            t2.Start();
            if(t1.Join(1000))
            {
                Console.WriteLine("threadfunction1 end");
            }
            else
            {
                Console.WriteLine("threadfunction1 still working");
            }
            if(t1.IsAlive)
            {
                for (int i = 1; i < 10; i++)
                {
                    Console.WriteLine("threadfunction1 still working...");
                    Thread.Sleep(500);                    
                }
            }
            Console.WriteLine("main end");
        }

        public static void ThreadFunction1()
        {
            Console.WriteLine("threadfunction1 start");
            Thread.Sleep(5000);
            Console.WriteLine("threadfunction1 end");
        }

        public static void ThreadFunction2()
        {
            Console.WriteLine("threadfunction2 start");
        }

 

转载于:https://www.cnblogs.com/gester/p/4870446.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值