This is example of Async calculation implementation in C# which works nearly in the same way as recently published post related to Java Async Programming
Task:
Execute parallel task on background and retrieve result of calculations once task is complete.
Implementation:
Lets start from our worker which will perform heavy calculations
using System;
using System.Threading;
namespace AsyncCalculations
{
class AsyncWorker
{
public string performLongAndHeavyCalculation(int dig1, int dig2)
{
Console.WriteLine("Worker: Starting job");
int sum = dig1 + dig2;
Thread.Sleep(3000);
Console.WriteLine("Worker: Job Complete");
return "Result of heavy calculation is: "+sum;
}
}
}
Well calculations are not that heavy 🙂
but 3 seconds of sleep could represent request to the server side database. There is nothing really to talk about, everything simple and straightforward.
Now lets have a look at our main thread – async caller:
using System;
using System.Runtime.Remoting.Messaging;
using System.Threading;
namespace AsyncCalculations
{
class AsyncCaller
{
public static void Main(string[] args)
{
new AsyncCaller();
}
//define delegate
private delegate string MyAsyncDelegate(int dig1, int dig2);
private bool gotResponse;
private string workerResponse;
public AsyncCaller()
{
gotResponse = false;
int num1 = 10;
int num2 = 30;
Console.WriteLine("Main Thread: Start");
Console.WriteLine("Main Thread: launching worker");
//create delegate
MyAsyncDelegate myDelegate = new MyAsyncDelegate(new AsyncWorker().performLongAndHeavyCalculation);
//execute async task
myDelegate.BeginInvoke(num1, num2, new AsyncCallback(onCallBack), null);
Console.WriteLine("Main Thread: worker executed");
//wait for a response
while(!gotResponse)
{
Console.WriteLine("Wating for worker to complete his job....");
Thread.Sleep(500);
}
//Display response result
Console.WriteLine("Main Thread: Worker says: "+workerResponse);
Console.WriteLine("Main Thread: Finished");
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
public void onCallBack(IAsyncResult result)
{
//recats result
AsyncResult res = (AsyncResult)result;
//retrieve delegate
MyAsyncDelegate myDeleg = (MyAsyncDelegate)res.AsyncDelegate;
//get response and set it to local variable
workerResponse = myDeleg.EndInvoke(result);
gotResponse = true;
}
}
}
Now lets talk about code:
1) Delegate – private delegate string MyAsyncDelegate(int dig1, int dig2);
the main thing to know about delegate is that delegate have to match to the method signature
in our case string is return type, dig1, dig2 – two integers as input params
2) Delegate Creation – MyAsyncDelegate myDelegate = new MyAsyncDelegate(new AsyncWorker().performLongAndHeavyCalculation);
if you will check “AsyncWorker” class, you would notice that string performLongAndHeavyCalculation(int, int) match to our delegate signature.
3) Executing Async with BeginInvoke – myDelegate.BeginInvoke(num1, num2, new AsyncCallback(onCallBack), null);
Async Execution consist of 3 params:
- Method input – in our case
num1andnum2which are dig1 and dig2 - Call back response – method which will be invoked when result is ready
- object – in our case it is null
4) On Call back event we getting delegate reference back
5) and getting result value by calling myDeleg.EndInvoke(result);
as simple as that 🙂
here is console output:
Main Thread: Start
Main Thread: launching worker
Main Thread: worker executed
Wating for worker to complete his job....
Worker: Starting job
Wating for worker to complete his job....
Wating for worker to complete his job....
Wating for worker to complete his job....
Wating for worker to complete his job....
Wating for worker to complete his job....
Wating for worker to complete his job....
Worker: Job Complete
Main Thread: Worker says: Result of heavy calculation is: 40
Main Thread: Finished
Press any key to exit...