[英]C# equivalent of Java awaitility
I would like to replicate something that I have in Java to C#.我想将 Java 中的内容复制到 C#。
I'm NOT looking for, or anything that will involve the driver:我不是在寻找,或任何涉及司机的东西:
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
I'm using the http://www.awaitility.org/ .我正在使用http://www.awaitility.org/ 。
Here is the code:这是代码:
public static void waitForElement(WebElement element) {
with()
.pollDelay(100, TimeUnit.MICROSECONDS)
.and()
.pollInterval(200, TimeUnit.MICROSECONDS)
.await()
.ignoreExceptions()
.until(() -> element.isDisplayed());
}
Thanks谢谢
I would do something like我会做类似的事情
public static async Task WaitForElementAsync(WebElement element)
{
await With(100, 200, true, () => element.isDisplayed());
}
private static async Task With(
int pollDeley,
int pollIntervall,
bool ignoreException,
Func<bool> until)
{
await Task.Delay(pollDeley);
var loop = true;
while (loop)
{
try
{
loop = !until();
if (!loop) break;
await Task.Delay(pollIntervall);
}
catch (Exception ex)
{
if (!ignoreException) throw;
}
}
}
but there might be a better solution if WebElement
has an event like IsDisplayedChanged
.但如果WebElement
有类似IsDisplayedChanged
的事件,可能会有更好的解决方案。
Also with this solution you introduce a async call line to your project (which in a web context can be beneficial), to avoid this you can replace the await Task.Delay(...)
with Thread.Sleep(...)
.此外,使用此解决方案,您还可以在项目中引入异步调用行(在 web 上下文中可能会有所帮助),为避免这种情况,您可以将await Task.Delay(...)
替换为Thread.Sleep(...)
。
Another solution would be to use a timer for the polling另一种解决方案是使用计时器进行轮询
private static async Task With(
int pollDeley,
int pollIntervall,
bool ignoreException,
Func<bool> until)
{
await Task.Delay(pollDeley);
var tcs = new TaskCompletionSource<bool>();
using (var timer = new Timer(pollIntervall))
{
void Poll(object sender, ElapsedEventArgs e)
{
try
{
if (until())
{
if (tcs.TrySetResult(true))
{
timer.Stop();
}
}
}
catch (Exception ex)
{
if (!ignoreException)
{
if (tcs.TrySetException(ex))
{
timer.Stop();
}
}
}
}
timer.Elapsed += Poll;
timer.Start();
await tcs.Task;
timer.Elapsed -= Poll;
}
}
I would like to replicate something that I have in Java to C#.我想将我在 Java 中的内容复制到 C#。
I'm NOT looking for, or anything that will involve the driver:我不是在寻找,或者任何会涉及到司机的东西:
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); WebDriverWait 等待 = 新 WebDriverWait(驱动程序,TimeSpan.FromSeconds(10));
I'm using the http://www.awaitility.org/ .我正在使用http://www.awaitility.org/ 。
Here is the code:这是代码:
public static void waitForElement(WebElement element) {
with()
.pollDelay(100, TimeUnit.MICROSECONDS)
.and()
.pollInterval(200, TimeUnit.MICROSECONDS)
.await()
.ignoreExceptions()
.until(() -> element.isDisplayed());
}
Thanks谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.