
In this course, we will cover the below topics
•Multithreading from basic to advance level
•Asynchronous Programming in C#
•how to write asynchronous programming using Task
•Parallel Programming
• Parallel For /Foreach in C#
•Parallel Invoke in C#
•Parallel Linq in C#
prerequisite
•Visual studio should install on system 2013 or higher version
•Basic knowledge of C# programming
•Willing to learn new things
What You will get from this Course
•Source code will be available as per the topic we cover.
•Confident on multithreading,asynchronous, and parallel programming
•Multitasking is the concept of running multiple application at a time.
•Ex. Windows operating system is the multitasking operating system
•A process is a part or component of the operating which is responsible for executing the program or application. So, to execute each and every program or application, there will be a process.
•To see all the services which is available you can go to run command and type
services.msc
•So, under the operating system, we have processes that running our applications. So under the process, an application runs. To run the code of an application the process will make use of a concept called Thread.
So under the operating system, we have processes that run our applications. So under the process, an application runs. To run the code of an application the process will make use of a concept called Thread.
•
•Generally when we talk about thread, so Thread is a lightweight process. A process has at least one thread which is commonly called the main thread that actually executes the application code.
• A single process can have multiple threads.
• All the threading-related classes are present in System. Threading namespace.
•All thread related function and properties are exist in below namespace
•using System. Threading;
Thread class contain some properties and method ,which we will discuss in this video
There are following states in the life cycle of a Thread in C#.
Unstarted
Runnable (Ready to run)
Running
Not Runnable
Dead (Terminated)
If we are working with a single-thread application it means all the code that exists in the application will be executed by a single thread only or we can say it will execute by the main thread.
What is the problem with single-thread applications?
For example, if method2 takes some time to execute, it can take time while get a huge data from the database or code execution time, and in this scenario,method3 has to wait until the method2 execution is complete, and it's not a good practice in the real-time scenario to write such kind of code.
To resolve the above single thread problem, C# provides the concept of multithreading.
So to implement the multithreading in the above code, we have to make some changes.
As of now for all 3 methods we are using only a single main thread, now we have to attach a separate thread for all methods and that respective thread will be responsible to execute the respective method code.
So when there are multiple threads that need to run in a program, the operating system is going to allocate some time period for each thread to execute.
The advantage of multi-thread is, that if any method takes time to execute, that time will not be wasted, in that time, other threading will be working on their respective methods. Apart from that, it gives advantages of maximum utilization of CPU resources.
In C#, the Thread class contains four constructors. If you go to the definition of Thread class then you can see the Constructors as shown below.
public Thread(ParameterizedThreadStart start);
public Thread(ThreadStart start);
public Thread(ParameterizedThreadStart start, int maxStackSize);
public Thread(ThreadStart start, int maxStackSize);
In this video, we will discuss public Thread(ThreadStart start); Constructor.
ThreadStart is a delegate and The ThreadStart delegate does not take any parameter as well as the return type is void.
Delegate:- A delegate is a type-safe function pointer means the signature of the delegate should be the same as the signature of the method.
We use the ParameterizedThreadStart delegate when the thread function accepts a parameter.
To make the type-safe thread function, we have to create a helper class, and that helper class constructor we pass the parameter and according to that, we perform the operation.
To retrieve the data from a thread function, first, we need to encapsulate the thread function and the data it requires in a helper class. To the constructor of the Helper class, we need to pass the required data as well as a delegate callback method.
•In C#, the Thread class provides the Join() method which allows one thread to wait until another thread completes its execution.
•If t is a Thread object whose thread is currently executing, then t. Join() causes the current thread to pause its execution until the thread it joins completes its execution.
•Join method also has an overload where we can specify the timeout.
• If we don't specify the timeout the calling thread waits indefinitely, until the thread on which Join() is invoked completes.
•his overloaded Join(int millisecondsTimeout) method returns a boolean. True if the thread has terminated otherwise false.
•Join is particularly useful when we need to wait and collect results from a thread execution or if we need to do some cleanup after the thread has been completed.
•IsAlive returns boolean. True if the thread is still executing otherwise false.
Protecting shared resources from concurrent access in multithreading is very important, we can protect shared resources in many scenarios.
in this video, we will discuss how to protect shared resources from concurrent access in multithreading using locking and Interlocked.Increment(); method
Protecting shared resources from concurrent access in multithreading is very important, we can protect shared resources in many scenarios.
in this video, we will discuss how to protect shared resources from concurrent access in multithreading using Monitor class.
Compare locking and monitor in multithreading, explaining how lock provides exclusive access to a shared resource and monitor offers advanced control.
•Monitor is also a locking mechanism that will ensure one thread is executing a piece of code at one time.
•Monitor is no different from a lock but the monitor class provides more control over the synchronization of various threads trying to access the same lock of code.
•Monitor locks objects. While you can pass a value type to Enter and Exit, it is boxed separately for each call.
•Monitor has signalling mechanisms, like wait , pulse and pulseall methods for signalling/communication between threads.
•Monitor.wait(): A thread wait for other threads to notify.
•Monitor.pulse(): A thread notify to another thread.
•Monitor.pulseAll(): A thread notifies all other threads within a process.
In our day to day programming with C# threading we come across the scenarios where we have to wait for signal of one thread to let the operation of some other thread to continue. This is simply known as signalling.
This is simplest signalling construct where calling WaitOne() blocks the current thread until other thread opens the signal be calling Set().
Working With ManualResetEvent in C#
Creating an Instance – We can create an instance of this signalling construct by passing true or false in the constructor. If we have false as argument if means that the watching threads will wait unless it is set.
If we pass true as argument the thread(s) wont wait and will continue with their operation.
WaitOne – Method used by the waiting threads to wait for the signalling construct. Whatever comes after the waitone will be executed one the threads are signaled.
Set() – Waiting threads are signaled by some other thread to continue with their operation by using Set method of ManualResetEvent.
Reset() – The threads are put into waiting state once again by calling the Reset() method of the manualResetEvent.
•AutoResetEvent is used to send signals between two threads.
•Both threads share the same AutoResetEvent object. Thread can enter into a wait state by calling WaitOne() method of AutoResetEvent object. When second thread calls the Set() method it unblocks the waiting thread.
How AutoResetEvent Works
AutoResetEvent maintains a boolean variable in memory. If the boolean variable is false then it blocks the thread and if the boolean variable is true it unblocks the thread.
When we instantiate an AutoResetEvent object, we pass the default value of the boolean value in the constructor. Below is the syntax of instantiating an AutoResetEvent object.
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
•Mutex is a synchronization primitive that grants exclusive access to the shared resource to only one thread.
• If a thread acquires a Mutex, the second thread that wants to acquire that Mutex is suspended until the first thread releases the Mutex.
•The Semaphore in C# is used to limit the number of threads that can have access to a shared resource concurrently.
•In other words, we can say that Semaphore allows one or more threads to enter into the critical section and execute the task concurrently with thread safety.
•deadlock in C# is a situation where two or more threads are unmoving or frozen in their execution because they are waiting for each other to finish.
•We can resolve Deadlock in multithreading by many ways
•1. using by acquiring locks in a specific order
•Using monitor.TryEnter()
•Mutex
Thread pool in C# is nothing but a collection of threads that can be reused to perform no of tasks in the background. Now when a request comes, then it directly goes to the thread pool and checks whether there are any free threads available or not. If available, then it takes the thread object from the thread pool and executes the task.
Once the thread completes its task then it again sent back to the thread pool so that it can reuse. This reusability avoids an application to create the number of threads and this enables less memory consumption.
Explore performance testing in C# by comparing thread creation versus the thread pool using stopwatch timing, highlighting the thread pool as the faster approach for multiple tasks.
Ways to find out how many processors you have on your machine?
•Using Task Manager
•Using msinfo32 Command
•Using dot net code.
Environment.ProcessorCount
•Using the command prompt
On the Windows command prompt write the following code and press enter
echo %NUMBER_OF_PROCESSORS%
•
In this section, we will see everything about Asynchronous Programming With C#.
we will discuss both synchronous and asynchronous methods.
we will learn about the Task and Async and Await
So I will see you in the next video
•In synchronous operations tasks are performed one at a time and only when one is completed, the following is unblocked. In other words, you need to wait for a task to finish to move to the next one
•What is Synchronous
•Synchronous programming is a process that starts happening together at the same time.
•A synchronous call waits for the method to complete before continuing with program flow.
•How bad is it?
•It badly impacts the UI that has just one thread to run its entire user interface code.
•Synchronous behavior leaves end users with a bad user experience and a blocked UI whenever the user attempts to perform some lengthy (time-consuming) operation.
•In synchronous operations tasks are performed one at a time and only when one is completed.
•A synchronous method call can create a delay in program execution which give bad user experience in real world.
•So to Overcome this problem we have asynchronous approach.
•In asynchronous approach we create a separate thread which perform another operation at same time.
•In asynchronous operations, we can perform more than 1 task at a time.
•In asynchronous operations, we can move to another task before the previous o.ne finishes
•Asynchronous Programming Model (APM) :-
• An asynchronous operation that uses the IAsyncResult design pattern
•It is implemented as two methods named BeginOperationName and EndOperationName that begin and end the asynchronous operation OperationName respectively.
•Event-based Asynchronous Pattern (EAP) :-
•Which is the event-based legacy model for providing asynchronous behaviour.
•A class that supports the Event-based Asynchronous Pattern will have one or more methods named MethodNameAsync.
• These methods may mirror synchronous versions, which perform the same operation on the current thread.
•The class may also have a MethodNameCompleted event and it may have a MethodNameAsyncCancel (or simply CancelAsync) method.
•Task based Asynchronous Pattern (TAP):-
•In .NET, The task-based asynchronous pattern is the recommended asynchronous design pattern for new development.
•It is based on the Task and Task<TResult> types in the System.Threading.Tasks namespace, which are used to represent asynchronous operations.
•Asynchronous Programming Model (APM) :-
•.NET framework 1.1 introduced something called Asynchronous Programming Model where we can have asynchronous versions of synchronous method implemented as a set of two methods called Begin<MethodName> and End<MethodName>
• An asynchronous operation that uses the IAsyncResult design pattern
•It is implemented as two methods named BeginOperationName and EndOperationName that begin and end the asynchronous operation OperationName respectively.
•
•For example, the FileStream class provides the BeginRead and EndRead methods to asynchronously read bytes from a file. These methods implement the asynchronous version of the Read method.
•Applications that do not need to block while the asynchronous operation completes can use one of the following approaches:
•
•Poll for operation completion status by checking the IsCompleted property periodically and calling EndOperationName when the operation is complete. For an example that illustrates this technique, see Polling for the Status of an Asynchronous Operation.
•
•Use an AsyncCallback delegate to specify a method to be invoked when the operation is complete. For an example that illustrates this technique, see Using an AsyncCallback Delegate to End an Asynchronous Operation.
•Use an AsyncCallback delegate to process the results of an asynchronous operation in a separate thread.
•The AsyncCallback delegate represents a callback method that is called when the asynchronous operation completes.
•The callback method takes an IAsyncResult parameter, which is subsequently used to obtain the results of the asynchronous operation.
•Event-based Asynchronous Pattern (EAP) :-
•Which is the event-based legacy model for providing asynchronous behavior.
•A class that supports the Event-based Asynchronous Pattern will have one or more methods named MethodNameAsync.
• These methods may mirror synchronous versions, which perform the same operation on the current thread.
•The class may also have a MethodNameCompleted event and it may have a MethodNameAsyncCancel (or simply CancelAsync) method.
•Basically, this pattern enforces a pair of methods and an event to collaborate and help the application execute a thread asynchronously
•
•Task based Asynchronous Pattern (TAP):-
•In .NET, The task-based asynchronous pattern is the recommended asynchronous design pattern for new development.
•It is based on the Task and Task<TResult> types in the System.Threading.Tasks namespace, which are used to represent asynchronous operations.
•Once we import the System.Threading.Tasks namespace, then we can create as well as access the task objects by using Task class.
•.NET framework provides Threading.Tasks class to let you create tasks and run them asynchronously.
•A task is an object that represents some work that should be done.
•The task can tell you if the work is completed and if the operation returns a result, the task gives you the result.
•Both the Thread class and the Task class are used for parallel programming in C#.
• A Thread is a lower-level implementation while a Task is a higher-level implementation.
• Thread class takes resources while a Task does not.
•Thread class also provides more control than the Task class.
•A Thread should be preferred for any long-running operations, while a Task should be preferred for any other asynchronous operations.
•The task can return a result. There is no direct mechanism to return the result from a thread.
•Task supports cancellation through the use of cancellation tokens. But Thread doesn’t.
•A task can have multiple processes happening at the same time. Threads can only have one task running at a time.
•We can easily implement Asynchronous using ’async’ and ‘await’ keywords.
•A new Thread()is not dealing with Thread pool thread, whereas Task does use thread pool thread.
•we are creating the task object using the Factory property which will start automatically.
•Starting with the .NET Framework 4.5, the Task.Run method provides the easiest way to create a Task object with default configuration values.
•The Run method allows you to create and execute a task in a single method call and is a simpler alternative to the StartNew method.
•It creates a task with the following default values: Its cancellation token is CancellationToken.
•From a performance point of view, the Task.Run or Task.Factory.StartNew methods are preferable to create and schedule the tasks.
•But, if you want to the task creation and scheduling separately, then you need to create the task separately by using Task class and then call the Start method to schedule the task execution for a later time.
Explore how the Task.WaitAll method blocks the main thread until all child tasks complete, contrasting it with thread join for synchronous vs asynchronous programming in C# and .NET.
•The .NET Framework also provides a generic version of the Task class i.e. Task<T>.
•Using this Task<T> class we can return data or value from a task. In Task<T>, T represents the data type that you want to returns as a result of the task.
•A continuation task (also known just as a continuation) is an asynchronous task that's invoked by another task, known as the antecedent, when the antecedent finishes.
•In asynchronous programming, it's common for one asynchronous operation, on completion, to invoke a second operation.
•Generally, when we invoke an asynchronous operation after the previous one had finished, we would have used callbacks.
•The ContinueWith function is a method available on the task that allows executing code after the task has finished execution. In simple words it allows continuation.
Explore creating continuations with multiple antecedents in C# using the continue with approach, showing how to coordinate tasks with lambda expressions for parallel execution in .NET.
•
•async and await keywords are used to create asynchronous methods.
•The async keyword turns a method into an async method, which allows you to use the await keyword in its body.
•When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete.
•await can only be used inside an async method.
•An async method typically contains one or more occurrences of an await operator, but the absence of await expressions doesn’t cause a compiler error.
there are three return types of any asynchronous function and they are:
Void
Task
Task<T>
•What is Parallel Programming?
•Parallel programming is a programming technique wherein the execution flow of the application is broken up into pieces that will be done at the same time (concurrently) by multiple cores, processors, or computers for the sake of better performance.
•Parallel Programming is a type of programming in which many calculations or the execution of processes are carried out simultaneously.
•What is Task Parallel Library (TPL) ?
•The Task Parallel Library (TPL) is a set of public types and APIs in the System.Threading and System.Threading.Tasks namespaces.
•The purpose of the TPL is to make developers more productive by simplifying the process of adding parallelism and concurrency to applications.
•Starting with .NET Framework 4, the TPL is the preferred way to write multithreaded and parallel code.
•What is the difference between the Parallel For loop and Standard C# for loop?
•In the case of the standard C# for loop, the loop is going to run using a single thread whereas, in the case of Parallel For loop, the loop is going to execute using multiple threads.
•The second difference is that, in the case of the standard C# for loop, the loop is iterated in sequential order whereas, in the case of Parallel For loop, the order of the iteration is not going to be in sequential order.
•The ParallelOptions class is one of the most useful classes when working with multithreading. This class provides options to limit the number of concurrently executing loop methods.
•
•The Parallel Invoke Method in C# is one of the most frequently used static method of the Parallel class.
•This Parallel Invoke method is used to launch multiple tasks that are going to be executed in parallel.
•The Parallel Invoke method is used to execute a set of operations (actions) in parallel.
•Parallel LINQ (PLINQ) is a parallel implementation of the Language-Integrated Query (LINQ) pattern.
•PLINQ implements the full set of LINQ standard query operators as extension methods for the System.Linq namespace and has additional operators for parallel operations.
•PLINQ combines the simplicity and readability of LINQ syntax with the power of parallel programming.
I welcome you all to this amazing course. Hope the learning would add value to your knowledge and you will learn to make an Application using the multithreading and asynchronous programming parallel programming in C#
Wishing you a happy learning. Please do comment and provide feedback on the course.
Requirements
Visual Studio 2013 or above
Before continuing on this course we should have basic knowledge in below technology. C#
This course is about .NET multithreading, asynchronous programming, and Parallel Programming with C# and Dotnet framework, namely the Task Parallel Library (TPL) and Parallel LINQ (PLINQ).
This course will teach you about:
Multitasking:- Concept of multitasking, and how multitasking works
Thread:- How to use thread in C#
Task Programming: how to create and run tasks, cancel them, wait on them and handle exceptions that occur in tasks.
Parallel Loops which us to iterate over the thread in C#
Parallel LINQ, the parallel version of . NET's awesome Language-Integrated Query (LINQ) technology.
Async/Await and . NET's support for asynchronous programming.
This course is suitable for:
Beginner and experienced .NET/C# developers
Anyone interested in multi-threading, asynchronous programming parallel programming
About project implementation
In this course, we will see each topic with a real-time example and we will see how to implement all concepts in Visual studio so we are able to understand it very well.
I recommend, please install visual studio 2013 or the above version so it will be helpful to implement logic in visual studio and you will learn every concept practically.
It will be very helpful if you have basic knowledge of C#.
I am glad that you successfully completed the course.
Hope you enjoyed it.
Keep growing.
Have a wonderful life ahead!!!!!