Thread lifetime

The lifetime of the thread depends on the method executing within that thread. Once the method is executed, CLR de-allocates the memory taken by the thread and disposes of. On the other hand, the thread can also be disposed of explicitly by calling the Interrupt or Abort methods.

Another very important factor to consider is exceptions. If the exceptions are not properly handled within a thread, they are propagated to the calling method and so on until they reach the root method in the call stack. When it reaches this point, CLR will shut down the thread if it is not handled.

For continuous or long-running threads, the shutdown process should be properly defined. One of the best approaches to smoothly shut down the thread is by using a volatile bool variable:

class Program 
{ 
 
  static volatile bool isActive = true;  
  static void Main(string[] args) 
  { 
    new Thread(new ParameterizedThreadStart
(ExecuteLongRunningOperation)).Start(1000); } static void ExecuteLongRunningOperation(object milliseconds) { while (isActive) { //Do some other operation Console.WriteLine("Operation completed successfully"); } } }

In the preceding code, we have used the volatile bool variable isActive, that decides if the while loop execute or not.

The volatile keyword indicates that a field may be modified by multiple threads that are executing at the same time. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times. To learn more about volatile, kindly refer the following URL:
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.255.169