Improving your C# Skills
上QQ阅读APP看书,第一时间看更新

Creating threads in .NET Core

In .NET Core, the threading API is the same as that used in the full .NET Framework version. A new thread can be created by creating a Thread class object and passing the ThreadStart or ParameterizedThreadStart delegate as a parameter. ThreadStart and ParameterizedThreadStart wrap a method that is invoked when the new thread is started. ParameterizedThreadStart is used for method containing parameters.

Here is a basic example that runs the ExecuteLongRunningOperation method on a separate thread:

static void Main(string[] args) 
{ 
  new Thread(new ThreadStart(ExecuteLongRunningOperation)).Start(); 
} 
static void ExecuteLongRunningOperation() 
{ 
  Thread.Sleep(100000); 
  Console.WriteLine("Operation completed successfully"); 
} 

We can also pass parameters while starting the thread and use the ParameterizedThreadStart delegate:

static void Main(string[] args) 
{ 
  new Thread(new ParameterizedThreadStart
(ExecuteLongRunningOperation)).Start(100000); } static void ExecuteLongRunningOperation(object milliseconds) { Thread.Sleep((int)milliseconds); Console.WriteLine("Operation completed successfully"); }

The ParameterizedThreadStart delegate takes an object as a parameter. So, if you want to pass multiple parameters, this can be done by creating a custom class and adding the following properties:

public interface IService 
{ 
  string Name { get; set; } 
  void Execute(); 
} 
 
public class EmailService : IService 
{ 
  public string Name { get; set; } 
  public void Execute() => throw new NotImplementedException(); 
 
  public EmailService(string name) 
  { 
    this.Name = name; 
  } 
} 
 
static void Main(string[] args) 
{ 
  IService service = new EmailService("Email"); 
  new Thread(new ParameterizedThreadStart
(RunBackgroundService)).Start(service); } static void RunBackgroundService(Object service) { ((IService)service).Execute(); //Long running task }

Every thread has a thread priority. When a thread is created, its priority is set to normal. The priority affects the execution of the thread. The higher the priority, the higher the precedence that will be given to the thread. The thread priority can be defined on the thread object, as follows:

static void RunBackgroundService(Object service) 
{ 
Thread.CurrentThread.Priority = ThreadPriority.Highest;
((IService)service).Execute(); //Long running task }

RunBackgroundService is the method that executes in a separate thread, and the priority can be set by using the ThreadPriority enum and referencing the current thread object by calling Thread.CurrentThread, as shown in the preceding code snippet.