Nov*_*tor 13 c# execution-time time-limiting
我有一个问题.我正在写一个基准测试,我有一个功能,而不是在2秒或大约5分钟后完成(取决于输入数据).如果执行时间超过3秒,我想停止该功能......
我该怎么做?
非常感谢!
sha*_*tap 50
嗯...,我有同样的问题,在阅读了这里的所有答案和推荐的博客之后,我为此付诸东流,
它让我执行任何带有时间限制的代码块,声明包装器方法
public static bool ExecuteWithTimeLimit(TimeSpan timeSpan, Action codeBlock)
{
try
{
Task task = Task.Factory.StartNew(() => codeBlock());
task.Wait(timeSpan);
return task.IsCompleted;
}
catch (AggregateException ae)
{
throw ae.InnerExceptions[0];
}
}
Run Code Online (Sandbox Code Playgroud)
并使用它来包装这样的任何代码块
// code here
bool Completed = ExecuteWithTimeLimit(TimeSpan.FromMilliseconds(1000), () =>
{
//
// Write your time bounded code here
//
});
//More code
Run Code Online (Sandbox Code Playgroud)
最好的方法是你的函数可以经常检查它的执行时间,以决定停止它需要太长时间.
如果不是这种情况,则在单独的线程中运行该函数.在你的主线程中启动一个3秒计时器.当计时器过去时,使用Thread.Abort()终止单独的线程(当然除非函数已经结束).请参阅函数文档中的示例代码和使用前预处理.
小智 5
private static int LongRunningMethod()
{
var r = new Random();
var randomNumber = r.Next(1, 10);
var delayInMilliseconds = randomNumber * 1000;
Task.Delay(delayInMilliseconds).Wait();
return randomNumber;
}
Run Code Online (Sandbox Code Playgroud)
和
var task = Task.Run(() =>
{
return LongRunningMethod();
});
bool isCompletedSuccessfully = task.Wait(TimeSpan.FromMilliseconds(3000));
if (isCompletedSuccessfully)
{
return task.Result;
}
else
{
throw new TimeoutException("The function has taken longer than the maximum time allowed.");
}
Run Code Online (Sandbox Code Playgroud)