如何在异步调用报告超时? [英] How to report timeout in Asynchronous call?
问题描述
我学习threading.My强度在一定值传递给计算方法,如果结果不会20毫秒内返回,我将报告操作超时。基于我understading我已经实现了code如下:
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;
}
问题:
(1)它是正确的方法来报告超时?
(1) Is it the proper way to report timeout ?
(2)我不会调用EndInvoke(),如果时间out.In这种情况下调用EndInvoke会()是必须的?
(2) I will not call EndInvoke() ,if the time is out.In such case calling the EndInvoke() is mandatory?
(3)我听说
即使你不想处理您的异步方法的返回值,你应该调用EndInvoke;否则,你可能每次内存泄露你开始使用的BeginInvoke异步调用
什么是记忆相关的风险?你可以给的例子吗?
What is the risk associated with memory ? can you give example ?
推荐答案
答案
(1)通常你刚才扔System.TimeoutException
(1) Usually you just throw System.TimeoutException
(2)原因EndInvoke会()需要的是,如果返回值(或抛出异常)有内存分配GC可能无法迅速清理。我还没有看到的地方,这是一个大问题的情况......但是这只是我。
(2) The reason EndInvoke() is required is that if return values (or exceptions thrown) have memory allocations the GC may not clean it up as quickly. I have not seen a case where this was a big problem... but that's just me.
如果您真的担心它,你可以只调用ThreadPool.QueueUserWorkItem是的大多的东西上面的异步调用就可以了。 (注:可以在的WinForms或其他线程依赖的环境问题)。反正你可以按照如下运行你自己的工作项目:
If your really worried about it you can just call ThreadPool.QueueUserWorkItem which is mostly what the above async invoke will do. (note: can be a problem in WinForms or other thread-dependent contexts). Anyway you can run your own work item as follows:
public static long Calc(CalcHandler fn, int a, int b, int c)
{
return Run<long>(TimeSpan.FromSeconds(20), delegate { return fn(a, b, c); });
}
public static T Run<T>(TimeSpan timeout, Func<T> operation)
{
Exception error = null;
T result = default(T);
ManualResetEvent mre = new ManualResetEvent(false);
System.Threading.ThreadPool.QueueUserWorkItem(
delegate(object ignore)
{
try { result = operation(); }
catch (Exception e) { error = e; }
finally { mre.Set(); }
}
);
if (!mre.WaitOne(timeout, true))
throw new TimeoutException();
if (error != null)
throw new TargetInvocationException(error);
return result;
}
这篇关于如何在异步调用报告超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!