This is part 1 of the article in this we will discuss about concepts of Asynchronous and Synchronous methodology in C# programming.
Learn C# Step By Step :- Part 1.
Learn C# Step By Step: - Part 2
Learn C# Step By Step (Concept of Class and Object): - Part 3
Learn C# Part 4b: Delegates, Multicast Delegates and Events.
Learn C# Part 5: Mini project - File Search.
Learn C# Part 6: Delegates - Lambda Expression, Expression Tree, Func<>, Action<> and Predicate<>
This article is part 1 and here we will discuss about concepts of Asynchronous and Synchronous methodology in C# programming.
In coming part 2 we will discuss more with the continuation of learning concept of Delegate, Multicast delegates and Events.
Creating new project
For ease of learning practically about above mentioned methodology, we will create a console application using C# language as new project within Visual Studio 2015 in this case name of the new project created is kept default “ConsoleApplication2” as given by Visual Studio.
Please Note creation of new project steps are going to be same as we had mentioned in our previous part 1 article of this series.
Creating new class library
Next, we will add a new Class library with that a new DLL file gets created which will be referred within “ConsoleApplication2”.
To create class library do right click on the Solution and click on Add > New Project.
With that a New Project window will be opened on the left side Visual C# under that select Windows and then select Class Library give name “FactorialCal” to this project.
Once the Class Library project is added it will be displayed under the Solution below to ConsoleApplication2 project.
On Class.cs write the following Factorial program which will achieve product(multiply it) of given number by user display result of it product. Like if we would like to calculate Factorial of numeric 5 is then thisFactorial program will calculate it and display its result as 5 = 5x4x3x2x1 = 120.
For that under the Factorial program we have “FactorialCal” named class followed within it has method which uses FOR loop for the same in order to achieve result.
The method given “Calculate” is the one who takes in number given by the user and does the Factorial calculation over it and gives out the result.
Number given by the user is stored in the result variable which has “int” as data type. Then with the help of “FOR loop” it will loop starting from value ‘1’ then incrementing it one by one until the desired number given by user is achieved. So for every loop result is getting multiplied by the earlier result value of “FOR loop”.
for (i = 1; i< number, i++)
result = result * i;
Finally it will return the result value with the help of following code line
Consuming Class library in Console Application
Now in order to use the above Factorial program which is written and available under Class Library in console application we need to do reference. For that on Solution Explorer simply doing right click on the “References” and clicking “Add Reference…” under “ConsoleApplication2” as shown in the image down below.
After clicking on Add Reference it will open Reference Manager screen. On the left side under this window click on Projects > Solution. Then on Solution it will show the “FactorialCal” class library just select it by doing a tick on the checkbox. And finally do a click on OK to close the Reference window.
Now if you see under “ConsoleApplication2” project after expanding “References” newly added “FactorialCal” class library can be seen as shown in the image down below.
Synchronous Calling method or function
Now go to Program.cs of ConsoleApplication2 and do the following: -
- As we want to the FactorialCal class write statement “using FactorialCalLab” which states importing of the namespace which is currently class library. Once the namespace is imported we can easily create object and give input to do get Factorial value of the input given.
- Create object the FactorialCal class by writing following line in order to use under console application.
FactorialLabobj = new FactorialLab();
- Write a line which will display on the console prompt “Calculation Started”
- Create variable called “result” with datatype as “int” and mention its object ‘obj’ with the method name and pass the input value, here given is 25. Frame code statement as below: -
int result = obj.Calculate(25);
- Next line written is to display Factorial output of the given value
- After the calculation is finished it will display the following statement on console prompt
- And finally a display statement which will be displayed on the console prompt
Now execute the program by pressing ctrl+F5 on keyboard and you can see the result has been executed successfully and displayed all the content. But here we are not able to make out the synchronous sequence as the value which we have entered is small. It gets executed very fast as soon as the console prompt is open and hardly difference is getting noticed.
So we will enter some big value to get Factorial result which will take time to process and get to see synchronous sequence.
Synchronous call with big value
We will use “BigInteger” datatype instead of “int” which can accommodate huge number within. For that we have to first add reference of System.Numerics from the Framework library on both Console Application as well Class Library “FactorialCal” as shown it the image down below.
Secondly we have import namespace of Numerics which belong to System class on both “Class.cs” of “FactorialCal” class library and “Program.cs” of “ConsoleApplication2”. In order to import namespace write this syntax “using System.Numerics;” at the top.
And then change “int” datatype to “BigInteger” wherever mentioned in both Console Application as well Class Library “FactorialCal”. On Console Application give input value whose factorial value need to be found.
Again execute the program and check its execution. After pressing ctrl+F5 its console prompt will open and gets started execution with first line “Calculation Started” and then factorial calculation will start since input value is big it will take time to complete it till then other lines will also not execute “Calculation Finished” and “Program Completed”.
This way of executing the program is termed as Synchronous programming where “caller” has to wait until “callee” send it response back and then “caller” completes it remaining execution.
Asynchronous methodology -Threading
In Asynchronous methodology “caller” does not have to wait until the “callee” has send its response. Caller can complete its execution and then later completecallee’s .
In order to achieve this logically C# has practical implementation called Threading where each process will use one thread to accomplish it and run simultaneously to other thread to achieve parallel execution or in order words they will execute asynchronously.
Next we will see introduction of Threading into our existing source code.
- For first import namespace of threading on “Program.cs” by writing following line code
- Now in order to make process as asynchronous introduce thread by creating object of the threading class whose namespace was imported using previous line code.
After displaying statement of “Calculation Started” create an object of thread class likewise which we did earlier. With this statement we will also pass the value to calculate its factorial within the parameter along with lambda expression denoted by “=>”. To know more on lambda expression get reference here
Thread t1 = new Thread(() =>obj.Calculate(1000000));
- Invoke the thread object “t1” to start its threading execution. Please note with this threading execution it will only do the Factorial calculation.
- While the other thread running is itself Main method which will display the “Calculation Started” statement.
So parallel execution will start with Main method running as first thread and then on other thread “t1” it will be running the Factorial calculation.
Now go and build the solution by clicking on the Rebuild option given on the top. After the solution is successfully build press combination key of ctrl+F5 on keyboard to display result on the console prompt and to know the whether process is actually working asynchronously as decided.
From the below image result first line under the Main method running on first thread is displaying result “Calculation Started” and other thread “t1” is running calculation of the factorial program output has not arrived but still next line from Main method running on first thread which contains “Calculation Finished” and final line of “Program Completed” has executed and displayed on the console screen. This clearly states that each process is running on different thread and the caller has not to wait for callee any more, in short asynchronous I achieved.
Still this asynchronous program has problem that caller had not been provided with the output of callee’s running process. This can be achieved by working with Delegates and events.
In the next article we will learn about the same in more details with concept and practical.
Below is C# learning video which is with practical project targeted for newbie’s: