Programming in C# Understanding Threading

What are threads

One CPU and events mean that if there are multiple tasks to be run, then if we have a processor intensive task that needs to run the App will freeze while we wait for task to complete. Threading allows up to use the power of multiple CPUs and allow multiple tasks to run at once allowing the UI to continue to work.

There is an overhead involved with this activity, but if you require a lot of threads for scaleability of responsiveness C# and .NET offer a lot of possibilities

 

Thread Class

The Thread class is the most basic way of doing threading, but is also could be dangerous due to the fact that it gives you full control.

Foreground/Background Threads

Used to keep an application alive, when all foreground tasks are stopped will the application be stopped, any background threads will be stopped.

ParameterizedThreadStart delgate

This method can be used if you want to pass some data through the start method ?

public static void ThreaMethod(object o){
   Console.writeline(o);
}

Thread t = new Thread(new ParameterizedThreadStart(ThreadMethod));
t.Start(5)

The above example will print out the number 5

Thread.About()

This terminates the current thread and is not to be recommended as it can leave a corrup state. A better way of doing this is to use a shared variable  that is used within the program and the delegate function.

T.Join()

This causes the application to wait until the tread finishes execution.

ThreadStatic / Thread Local

Thread static allows a thread to store a local copy of a variable and not share with the main application.

Thread.CurrentThread

This .NET class provides useful information about the currently running thread

Thread Pools

Queue a work item for use as a work item that you pass it to the thread pool. When a thread is available the Thread pool will pick up the work item and execute it.

The threadpool limits the amount of current tasks but gives many advantages.

There is better control of the tasks running and will stop a system from overloading so easially. It also has functions to help kill the Thread if it is not being used.

You must be careful sharing state as it could be shared using multiple operations

Leave a Reply

Your email address will not be published. Required fields are marked *