0

I want to run multiple windows of Chrome browser parallely. This works fine for 2 or sometimes 3 windows, but when I run 4 or more windows, browsers are opened but only one of them is running while others are just left blank.

Here is my code

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
}

The problem is, OpenWebsiteAndTest method is executed for only one of the browser instances and the code inside it is never executed for other windows

I think I'm either doing something wrong, or either doing it in a bad way. I want my application to open up to 9 windows and execute them simultaneously as per client's need.

Vishal Afre
  • 1,013
  • 3
  • 12
  • 39
  • If you put tracepoints in `OpenWebsiteAndTest` to output the value of `index`, does the output show expected result of `1, 2, 3, 4...` etc? Or does it show all one number (or does it skip a couple numbers)? – Keith Stein Jul 20 '20 at 16:41
  • Hi Vishal, was my reply helpful? – TimonYang Aug 24 '20 at 07:57

1 Answers1

4

Keith Stein mentioned the crux of the problem, all your indexes are the same.

If you check your List using breakpoint, you will see this.

Although a bit counterintuitive, this is how closure work.

Check the link below to learn more about closure.

Access to foreach variable in closure warning

Captured variable in a loop in C#

To make the program work, you need to create a copy of the variable in the loop, and then use this copy as the parameter.

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