I am learning threading.My intension is to pass some values to a method for calculation,if the result will not be returned within 20 ms,i will report "Operation timeout".Based on my understading i have implemented the code as follows:
public delegate long CalcHandler(int a, int b, int c);
public static void ReportTimeout()
{
CalcHandler doCalculation = Calculate;
IAsyncResult asyncResult =
doCalculation.BeginInvoke(10,20,30, null, null);
if (!asyncResult.AsyncWaitHandle.WaitOne(20, false))
{
Console.WriteLine("..Operation Timeout...");
}
else
{
// Obtain the completion data for the asynchronous method.
long val;
try
{
val= doCalculation.EndInvoke(asyncResult);
Console.WriteLine("Calculated Value={0}", val);
}
catch
{
// Catch the exception
}
}
}
public static long Calculate(int a,int b,int c)
{
int m;
//for testing timeout,sleep is introduced here.
Thread.Sleep(200);
m = a * b * c;
return m;
}
Questions :
(1) Is it the proper way to report timeout ?
(2) I will not call EndInvoke() ,if the time is out.In such case calling the EndInvoke() is mandatory?
(3) I heard that
"Even if you do not want to handle the return value of your asynchronous method, you should call EndInvoke; otherwise, you risk leaking memory each time you initiate an asynchronous call using BeginInvoke"
What is the risk associated with memory ? can you give example ?