Nice reference for C# evolution Part 4

Csharp
Csharp

Nice reference for C# evolution Part 4

Welcome to CodeSpread!

We completed till C# 4.0 introductions in last article,C# 3.0 in this article and C# 2.0 in first article . We will forward our journey with C# 5.0 features.

C# 5.0

Async Feature

There are new major additions to C#, two new keywords added to the C# 5.0 language are ‘async’ and ‘await’. First of all, these are only keywords introduced to simplify asynchronous programming.

What is Asynchronous Programming?

Let’s talk about illusion, Why? Because when we ask a machine to perform many tasks in parallel,  a thread scheduler switches between tasks running on different threads for a very small time frame giving us the illusion of parallelism.It can really happen if the processor has multiple cores or every core can execute several hardware threads.

Let’s say one main program asks the other supporting program to run on a different thread but didn’t wait for it to return any result . When the result is ready, a special ‘callback’ method is called to suggest the original program that supporting program have finished execution and results are ready.In this way, main program continues its operation without any pause or wait.

Asynchronous Programming, Before C# 5.0?

The .NET Framework provides three patterns for performing asynchronous operations:

  • Asynchronous Programming Model (APM) pattern (also called the IAsyncResult pattern), where asynchronous operations require Begin and End methods (for example, BeginWrite and EndWrite for asynchronous write operations). This pattern is no longer recommended for new development.
  • Event-based Asynchronous Pattern (EAP), which requires a method that has the Async suffix, and also requires one or more events, event handler delegate types, and EventArg-derived types. EAP was introduced in the .NET Framework 2.0. It is no longer recommended for new development.
  • Task-based Asynchronous Pattern (TAP), which uses a single method to represent the initiation and completion of an asynchronous operation. TAP was introduced in the .NET Framework 4 and is the recommended approach to asynchronous programming in the .NET Framework.
reference: http://msdn.microsoft.com/en-us/library/jj152938.aspx

Example of APM: Let us consider the famous example of Read method


public override int Read(byte[] array, int offset, int count)

This is the synchronous version of the method and blocks the calling thread until read is complete.The asynchronous version of the method is


public IAsyncResult BeginRead( byte [] buffer, int offset,int count,
AsyncCallback callback, object state);

public int EndRead(IAsyncResult asyncResult);

  • BeginRead starts the execution of the method in different thread.
  • EndRead waits for the pending operation to get complete.

There are different mechanisms of asynchronous execution.

  1. Polling : Checks for completion of tasks at regular intervals
  2. Waiting for Completion: Perform other tasks before asking for completion status of other thread.
  3. Completion Notification: Automatically gets called when status is complete.
  4. Fire and Forget: Don’t care about result.

Asynchronous Programming, After C# 5.0?

All asynchronous operations works via a method that returns Task or Task<TResult>.The ‘async’ keyword is used to declare an asynchronous function, which is a method that either returns void, a Task, or a Task<T>.Inside the asynchronous function, there must be at least one ‘await’ expression. It instructs the compiler that the code which follows must not execute until the result of the awaited expression is available.  This is done by using await on any expression that evaluates to a Task or Task<T>.


public async void TryAsync ()
{
var demoClass = new DemoClass ();

int result = await Task<int>.Factory.StartNew(() => demoClass.Add ();
}

These two  keywords opened a door to explore more opportunities in asynchronous programming through simpler ways.

Caller Information

This feature have helped us in logging which was not a exclusive feature of .Net and was done with a bit of negligence earlier. We can take an example of logging, we used to do earlier.


private static void Log(string methodName,string errormessage)
{
Console.WriteLine("{0} : {1} ", methodName,errormessage);
}

Now, C# 5.0 came with a powerful feature ‘Caller information attribute’.With the help of this feature, following information is available.

  • CallerFilePathAttribute: Full path of the source file that contains the caller. This will be file path at compile time.
  • CallerLineNumberAttribute:  Line number of source file from where the method is called.
  • CallerMemberNameAttribute: Method or property name of the caller.

public void Log( [CallerMemberName] string methodName= "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
Console.WriteLine("{0} : {2} : {3}", methodName,
sourceFilePath ,sourceLineNumber );

}

Isn’t it cool?

With this article, we have finished the series “Nice reference for C# Evolution”. I hope you have enjoyed reading them. Please share your feedback here or mail it to admin@codespread.com. You can also become a member of codespread.com by sending one of your articles to the emailId.

Author: hershey

A passion for knowledge drives me to do programming, A passion for programming drives me to create something different, A passion for creation drives me to spread the knowledge.

Share This Post On

0 Comments

  1. nice superb explaination

    Post a Reply
  2. thanks for the tutorial
    I am having a problem.
    The feature “Create SQL server database” isn’t available , I can’t select it.
    Can you help, please ?

    Post a Reply

Submit a Comment

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

More from CodeSpread:

  • Nice reference for C# evolutionNice reference for C# evolutionWhile going through some posts on MSDN, I came across this beautiful image which can be termed as a one stop solution for C# evolution. This is a gift reference, I would like to share with my frien...
  • Nice reference for C# evolution Part 2Nice reference for C# evolution Part 2We completed till C# 2.0 introductions in last article. We will forward our journey with C# 3.0 features. C# 3.0 Lambda Expressions: Last article, we discussed anonymous function and how they ex...
  • Nice reference for C# evolution Part 3Nice reference for C# evolution Part 3We completed till C# 3.0 introductions in last article and C# 2.0 in this article . We will forward our journey with C# 4.0 features. C#4.0 Late Binding (Dynamic) Late binding is always presumed...
  • C#: Singleton Design PatternC#: Singleton Design PatternWe know the existence of a design pattern is dependent on a recurring problem. Once the problem is identified, then a well established solution is proposed theoretically and different implementatio...
  • Tip : Code Structure C#Tip : Code Structure C#As a developer, I always stress on developing a habit of following the best practices to structure the code. It helps me to easily navigate through the code and also saves a lot of effort in search...
  • Agile Encounters UnpredictabilityAgile Encounters UnpredictabilityWhat is Agile? Wikipedia says “Agile software development is a group of software development methods based on iterative and incremental development, where requirements and solutions evolve through...
  • Concepts: S O L I DConcepts: S O L I DSOLID - Object oriented programming principles. May be its easy to forget these principles  but for creating a reusable code or maintainable code, people will always have to come back and check ...
  • Get Educated: C# language 5.0 SpecificationsGet Educated: C# language 5.0 SpecificationsVery often,Developers ask me to write something about C# Language Specifications and I always ask them to refer Microsoft Download center. I think this is a pretty easy act as C# Language Specifica...