locked
Could static thread be stopped in Kestrel on Linux without manual abort? RRS feed

  • Question

  • User-1350516731 posted
    public class HomeController {
    
    public static Thread Thread = new Thread(new ThreadStart(Work));
    
    public ViewResult Index()
    {
    if(!Thread.IsAlive && DateTime.Now < new DateTime(2020,12,31))
        Thread.Start()
    
    return View();
    
    }
    
    public static void Work()
    {
    }
    
    }

    What reasons could lead to Thread abort in this piece of code rather than manual server machine stop on Linux if we call Index only once a year?

    Thursday, April 30, 2020 8:22 AM

All replies

  • User-854763662 posted

    Hi Alex9 ,

    What reasons could lead to Thread abort in this piece of code rather than manual server machine stop on Linux if we call Index only once a year?

    Static threads will not stop by themselves. In general, a thread is stopped :  after running the Work() method, or you call the Abort() method of the thread, or an exception is thrown in the thread.

    Best Regards,

    Sherry

    Friday, May 1, 2020 9:20 AM
  • User-474980206 posted

    static variables are initialized on the first reference. so the code

    if(!Thread.IsAlive && DateTime.Now < new DateTime(2020,12,31))
    

    the first time Thread.IsAlive is run, it calls the initialization of Thread (poor practice to use a class name as a variable). Your initializer:

    public static Thread Thread = new Thread(new ThreadStart(Work));
    

    starts a thread, which exits quickly as it has no code to execute. 

    Friday, May 1, 2020 3:19 PM