.NET构建的循环和超时 [英] .net construct for while loop with timeout
问题描述
我通常采用一个while循环继续尝试一些操作,直到操作成功或超时时间:
布尔成功= FALSE
INT经过= 0
而((成功)及!及(已过< 10000))
{
视频下载(1000);
经过+ = 1000;
成功= ...一些操作...
}
我知道有一对夫妇的方式来实现这一点,但基本的一点是,我反复尝试一些操作睡眠,直到成功,或者我在总睡太久了。
有一个内置的.NET类/方法/等,以拯救我重新写这个模式所有的地方?也许输入是Func键(布尔)和超时?
修改的
感谢所有谁贡献。我选择了睡眠()方法,因为它是最复杂的,我完全防复杂=)这是我(仍然需要进行测试)执行力度:
公共静态布尔RetryUntilSuccessOrTimeout(Func键<布尔>的任务,时间跨度超时,时间跨度暂停)
{
如果(pause.TotalMilliseconds℃,)
{
抛出新的ArgumentException(暂停必须与GT; = 0毫秒);
}
变种秒表= Stopwatch.StartNew();
做
{
如果(任务()){返回true; }
Thread.sleep代码((INT)pause.TotalMilliseconds);
}
而(stopwatch.Elapsed<超时);
返回false;
}
您可以换一个方法,你的算法:
公共BOOL RetryUntilSuccessOrTimeout(Func键<布尔>的任务,时间跨度时间跨度)
{
布尔成功= FALSE;
INT经过= 0;
而((成功)及!及(已过< timeSpan.TotalMilliseconds))
{
Thread.sleep代码(1000);
经过+ = 1000;
成功=任务();
}
返回成功;
}
然后:
如果(RetryUntilSuccessOrTimeout(()=> SomeTask(ARG1,ARG2),TimeSpan.FromSeconds(10)))
{
//任务成功
}
I commonly employ a while loop that continues to try some operation until either the operation succeeds or a timeout has elapsed:
bool success = false
int elapsed = 0
while( ( !success ) && ( elapsed < 10000 ) )
{
Thread.sleep( 1000 );
elapsed += 1000;
success = ... some operation ...
}
I know there a couple of way to implement this, but the basic point is that I repeatedly try some operation with a sleep until success or I've slept too long in aggregate.
Is there a built-in .net class/method/etc to save me from re-writing this pattern all over the place? Perhaps input is an Func(of bool) and the timeout?
Edit
Thanks to all who contributed. I opted for the sleep() approach because it was the least complicated and I'm totally anti-complexity =) Here's my (still needs to be tested) implimentation:
public static bool RetryUntilSuccessOrTimeout( Func<bool> task , TimeSpan timeout , TimeSpan pause )
{
if ( pause.TotalMilliseconds < 0 )
{
throw new ArgumentException( "pause must be >= 0 milliseconds" );
}
var stopwatch = Stopwatch.StartNew();
do
{
if ( task() ) { return true; }
Thread.Sleep( ( int )pause.TotalMilliseconds );
}
while ( stopwatch.Elapsed < timeout );
return false;
}
You could wrap your algorithm in a method:
public bool RetryUntilSuccessOrTimeout(Func<bool> task, TimeSpan timeSpan)
{
bool success = false;
int elapsed = 0;
while ((!success) && (elapsed < timeSpan.TotalMilliseconds))
{
Thread.Sleep(1000);
elapsed += 1000;
success = task();
}
return success;
}
and then:
if (RetryUntilSuccessOrTimeout(() => SomeTask(arg1, arg2), TimeSpan.FromSeconds(10)))
{
// the task succeeded
}
这篇关于.NET构建的循环和超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!