我正在学习线程。我的意图是将一些值传递给一个计算方法,如果结果将不会在20毫秒内返回,我会报告“操作超时”。基于我的内容,我已经实现了代码如下:如何在异步调用中报告超时?
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;
}
问题:
(1)是否有报告超时的正确方法? (2)如果时间到了,我不会调用EndInvoke()。在这种情况下调用EndInvoke()是强制性的吗?
(3)我听说
“即使你不想处理您的异步方法的返回值,你应该调用EndInvoke;否则,你可能每次启动时泄漏内存使用BeginInvoke进行异步调用“
与内存相关的风险是什么?你能举个例子吗?