Introduction
A few days ago, in our organization, we were trying to implement asynchronous programming (obviously in C# with Visual Studio 2010). First of all, Visual Studio 2010 targets the .NET Framework 4.0, and asynchronous programming is the concept of C# 5.0 that demands the .NET Framework 4.5 to compile and run.
The problem starts here. We are using Visual Studio 2010. The highest version of the .NET Framework that it supports is 4.0, and we are very much interested in implementing the asynchronous style in applications. Our project and source version control and other related software are licensed for Visual Studio 2010. So, what is the solution? We need to use Visual Studio 2012 (at least) to use .NET Framework 4.5, and then we are able to use the features of C# 5.0. (Ok, you are suggesting the use of the async CPT in VS2010). Believe me, I have tried the async CPT in VS2010, but it is not fully supported. (Let's not create a debate with this topic, proceed with our explanation). In this article, we will see how to implement an asynchronous style in C# applications. (Yes, even in .NET 4.0).
Implement By Delegate
This will be our first approach to implementing the asynchronous style. Let's implement a small example to understand it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Asynchronous
{
class Program
{
delegate void delHugeTask();
static void Main(string[] args)
{
// Create object to delegate
delHugeTask objHugeTask = new delHugeTask(HugeTask);
// Call the delegate asynchronously
objHugeTask.BeginInvoke(new AsyncCallback(callbackFunction), objHugeTask);
Console.WriteLine("Main Task finished. Waiting for Huge Task");
Console.ReadLine();
}
// Callback function to return result from Huge Task function
public static void callbackFunction(IAsyncResult obj)
{
}
public static void HugeTask()
{
System.Threading.Thread.Sleep(5000);
Console.WriteLine("Huge Task Finished");
}
}
}
This example is quite simple to understand. We have created one function called "HugeTask()" that has only two lines of code but is huge in nature. (Ha. Ha..., Yah, we are making a delay intentionally.) We will now call this function asynchronously. In other words, our program will not wait for the function.



GeorgiPosted Nov 20, 2013, 1:00 PM
Nice article. I added to your first C# code for .NET 4.0 as an experiment some code to do something in Main() while waiting the huge task ... works fine.
Ck NitinPosted Sep 23, 2013, 7:25 AM
I am your fan man. love to read your every article