Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

Nice reference for C# evolution: Part 4

, 29 Jan 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
We will forward our journey with C# 5.0 features.

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.

Related posts:

  1. Nice reference for C# evolution Part 3
  2. Nice reference for C# evolution
  3. Nice reference for C# evolution Part 2

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Himanshu DS
Web Developer CodeSpread.com
India India
I am a regular developer working on c#,asp.net,sql,cms,digital marketing related sites. Through my blog, I am showing the non-technical part of our daily technical terms and processes which can be used to describe it to a layman.Sometimes I write basic technical posts also.
Follow on   Twitter

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150327.1 | Last Updated 29 Jan 2013
Article Copyright 2013 by Himanshu DS
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid