首页 > 编程 > .NET > 正文

.net让线程支持超时的方法实例和线程在执行结束后销毁的方法

2024-07-10 12:44:20
字体:
来源:转载
供稿:网友


.net让线程支持超时

使用 CancellationTokenSource
代码如下:
private static void TimeoutTest1()
        {
            var cts = new CancellationTokenSource();

            var thread = new Thread(() =>
            {
                Console.WriteLine(String.Format("线程{0}执行中", Thread.CurrentThread.ManagedThreadId));
                Thread.Sleep(10000);
                Console.WriteLine(String.Format("线程{0}执行中", Thread.CurrentThread.ManagedThreadId));
            });

            cts.Token.Register(() =>
            {
                thread.Abort();
            });
            cts.CancelAfter(1000);

            thread.Start();
            thread.Join();

            Console.WriteLine(String.Format("线程{0}的状态:{1}", thread.ManagedThreadId, thread.ThreadState));
        }

这里采用了 Abort 终止了线程,CancellationTokenSource 也支持其它模式,可以去官方看看文档。

使用 Join

代码如下:
private static void TimeoutTest2()
        {
            var thread = new Thread(() =>
            {
                Console.WriteLine(String.Format("线程{0}执行中", Thread.CurrentThread.ManagedThreadId));
                Thread.Sleep(10000);
                Console.WriteLine(String.Format("线程{0}执行中", Thread.CurrentThread.ManagedThreadId));
            });

            thread.Start();
            thread.Join(1000);
            thread.Abort();

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表