C# stop thread after specified timespan

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

namespace ConsoleApp72
{
    internal class Program
    {
        static Thread t1 { get; set; }
        static System.Timers.Timer tmr { get; set; }
        static void Main(string[] args)
        {
           
            try
            {
                tmr = new System.Timers.Timer();
                tmr.Elapsed += Tmr_Elapsed;
                tmr.Interval = 5000;
                tmr.Start();
                t1 = new Thread(() =>
                {
                    PrintNum(10);
                });
                t1.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("Hello, World!");
            Console.ReadLine();
        }

        private static void Tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                if(t1.IsAlive)
                {
                    Console.WriteLine("t1 aborted!");
                    t1.Abort();
                    tmr.Stop();
                    Console.WriteLine("Timer stopped!");
                }                
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        static void PrintNum(int num)
        {
            for (int i = 0; i < num; i++)
            {
                Console.WriteLine(i);
                Thread.Sleep(1000);
            }
        }
    }
}

 

posted @ 2024-09-10 18:51  FredGrit  阅读(18)  评论(0)    收藏  举报