Click here to Skip to main content
15,892,537 members
Articles / Programming Languages / C# 5.0

Nice Reference for C# Evolution: Part 4

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
29 Jan 2013CPOL4 min read 6.8K   7  
We will forward our journey with C# 5.0 features

We completed till C# 4.0 introduction in the last article, C# 3.0 in this article and C# 2.0 in the first article. We will continue 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 programs have finished execution and results are ready. In this way, the 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.

C#
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:

C#
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 work 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>.

C#
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 has 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.

C#
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, the 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.
C#
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
  2. Nice reference for C# evolution Part 2
  3. Nice reference for C# evolution Part 3

License

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


Written By
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.

Comments and Discussions

 
-- There are no messages in this forum --