Fáb*_*nes 3 .net c# asynchronous timeout
如何在时间范围内从方法或属性返回任何类型的数据,如果在该时间范围内返回任何数据,则抛出异常?
我有一个简单的方法来执行一个简单的任务,一旦执行该方法返回一个值,如果在100毫秒内返回任何值,我希望该方法被中止并抛出异常,例如TimeoutException
,例如,任何类型的例外,只要它完成任务.
如果您使用的是.NET 3.5并且无法使用Parallel Extensions,则可以使用异步委托.这具有额外的好处,即重新抛出该方法在调用线程上抛出的异常.此示例中的超时逻辑依赖于WaitHandle,如leppie所述.
public static T EvaluateAsync<T> (this Func<T> func, Timespan timeout)
{
var result = func.BeginInvoke(null, null);
if (!result.AsyncWaitHandle.WaitOne(timeout))
throw new TimeoutException ("Operation did not complete on time.");
return func.EndInvoke(result);
}
static void Example()
{
var myMethod = new Func<int>(ExampleLongRunningMethod);
// should return
int result = myMethod.EvaluateAsync(TimeSpan.FromSeconds(2));
// should throw
int result2 = myMethod.EvaluateAsync(TimeSpan.FromMilliseconds(100));
}
static int ExampleLongRunningMethod()
{
Thread.Sleep(1000);
return 42;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
301 次 |
最近记录: |