我目前正在使用Selenium WebDriverWait
来等待我不需要IWebDriver
功能的情况。我的代码如下所示:
public static T WaitForNotNull<T>(this IWebDriver driver, Func<T> func)
{
var result = default(T);
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(d => (result = func()) != null);
return result;
}
public static void WaitForNull<T>(this IWebDriver driver, Func<T> func)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(d => func() == null);
}
在.Net中是否有类似的构造我可以使用而不是WebDriverWait?
答案 0 :(得分:1)
答案是
在.NET Framework中没有这样的东西,你必须自己编写这样的方法。
答案 1 :(得分:0)
这是原始的直到实施(source)。你可以改进IMO。
如果您不想阻止调用线程(在UI线程的情况下),您可以轻松使用async \ await模式
public TResult Until<TResult>(Func<T, TResult> condition)
{
if (condition == null)
{
throw new ArgumentNullException("condition", "condition cannot be null");
}
var resultType = typeof(TResult);
if ((resultType.IsValueType && resultType != typeof(bool)) || !typeof(object).IsAssignableFrom(resultType))
{
throw new ArgumentException("Can only wait on an object or boolean response, tried to use type: " + resultType.ToString(), "condition");
}
Exception lastException = null;
var endTime = this.clock.LaterBy(this.timeout);
while (true)
{
try
{
var result = condition(this.input);
if (resultType == typeof(bool))
{
var boolResult = result as bool?;
if (boolResult.HasValue && boolResult.Value)
{
return result;
}
}
else
{
if (result != null)
{
return result;
}
}
}
catch (Exception ex)
{
if (!this.IsIgnoredException(ex))
{
throw;
}
lastException = ex;
}
// Check the timeout after evaluating the function to ensure conditions
// with a zero timeout can succeed.
if (!this.clock.IsNowBefore(endTime))
{
string timeoutMessage = string.Format(CultureInfo.InvariantCulture, "Timed out after {0} seconds", this.timeout.TotalSeconds);
if (!string.IsNullOrEmpty(this.message))
{
timeoutMessage += ": " + this.message;
}
this.ThrowTimeoutException(timeoutMessage, lastException);
}
Thread.Sleep(this.sleepInterval);
}
}