【问题标题】:WPF running multiple tasks (selenium webdrivers) parallely not working properlyWPF 并行运行多个任务(selenium webdrivers)无法正常工作
【发布时间】:2020-11-09 08:53:00
【问题描述】:

我想并行运行 Chrome 浏览器的多个窗口。这适用于 2 个或有时 3 个窗口,但是当我运行 4 个或更多窗口时,浏览器会打开,但只有一个在运行,而其他的则保持空白。

这是我的代码

IWebDriver[] driver = new IWebDriver[forms.Length];
initDriver();    // custom method to initialize driver array using ChromeDriver

...

List<Action> actions = new List<Action>();
int i = 0;
foreach (string form in forms)
{
    actions.Add(() => OpenWebsiteAndTest(form, i));
    i++;
}

using (var collection = new BlockingCollection<int>())
{
    Parallel.Invoke(actions.ToArray());
}

private void OpenWebsiteAndTest(string formName, int index)
{
    // below website is only opened in one of the browsers
    driver[index].Navigate().GoToUrl("https://www.myurl.com");
    ...
    doTests(formName);    // custom method to automate the website and perform some tests
}

问题是,OpenWebsiteAndTest 方法仅对其中一个浏览器实例执行,其中的代码永远不会在其他窗口中执行

我认为我要么做错了什么,要么做错了事。我希望我的应用程序最多可以打开 9 个窗口并根据客户的需要同时执行它们。

【问题讨论】:

  • 如果你把跟踪点放在OpenWebsiteAndTest中输出index的值,输出是否显示1, 2, 3, 4...等的预期结果?还是显示所有一个数字(或跳过几个数字)?
  • 嗨,Vishal,我的回复有帮助吗?

标签: c# wpf visual-studio selenium selenium-webdriver


【解决方案1】:

Keith Stein 提到了问题的症结所在,你所有的索引都是一样的。

如果你使用断点检查你的列表,你会看到这个。

虽然有点违反直觉,但这就是闭包的工作原理。

查看下面的链接以了解有关关闭的更多信息。

Access to foreach variable in closure warning

Captured variable in a loop in C#

要让程序工作,你需要在循环中创建一个变量的副本,然后使用这个副本作为参数。

        int i = 0;
        foreach (string form in forms)
        {
            int copy = i;
            actions.Add(() => OpenWebsiteAndTest(form, copy));
            i++;
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 2016-03-11
    相关资源
    最近更新 更多