Monday, 23 December 2013

Multithreading or Threading which that is (part 1)

To set the scene in the discussion and journey towards mastering asynchronous programming,  we will start with the good old multi-threading paradigm. though the use of raw threads in writing concurrent code have dwindled recently ( due to the surfacing of higher level abstractions like Task) yet understanding threading will surely serve as a bedrock for understanding those higher level concepts ( lets face it higher level or not, all of it if am very correct here end up running in the good old threads)

The Thread class is located in the System.Threading namespace. This namespace was added to .net framework as far back as version 1.0. Threads (though the one in .net framework has been tweaked by the CLR for its purpose) are what the Operating system executes our codes in.

Enough of the grammar! (Yeah lets get to the code).

The thread constructor has two overloads:


  1.  One that takes an action method (i.e.  A delegate with a void return method and no parameters)
  2.  One that takes in a parametrized action method ( i.e. A delegate with a void return method that takes in an object parameter)
new Thread(/*Action delegate enter here */);
new Thread(/* Parametrized action delegate */).Start(/*Parameter goes here */);

The second overload is less popular due to the fact that better ways has been discovered to pass data to an action delegate that is being executed by the thread.

When a thread is created, it doesn't start  to execute immediately rather it has to be started before its execution begins.

new Thread(() => {/* Code to execute here */}).Start();

Once the thread's start method is called, the thread will start its execution and will run from start to finish and then exit. A thread that has executed its action method cannot be reused. Usually, a .net thread can exists in either of two modes : as a foreground thread or as a background thread. The major difference is that foreground thread keeps the application running even after the main thread that created it have exited but the reverse is the case with background thread that is aborted prematurely immediately the main thread that birthed it dies. But do not be troubled though, every new thread is created as a foreground thread.You can change the threads' mode by truning the IsBackground property to true. 

No comments:

Post a Comment