How can I close Chrome driver and clear from memory in Selenium C# and SpecFlow using a parallel testing setup?

Currently when running tests, Chrome driver's stack up and are never fully closed.
Have tried using:

driver.Close();
driver.Quit();
driver.Dispose();

Relating to this discussion

But the Chrome drivers still seem to exist after tests have run / finished.

After scenario hook:

        [AfterScenario]
public void AfterScenario()
{
    var driver = _objectContainer.Resolve<IWebDriver>();
    driver?.Quit();
    driver?.Dispose();
}

After feature hook:

    [AfterFeature]
public static void AfterFeature(FeatureContext featureContext)
{
    var driverService = featureContext.Get<ChromeDriverService>();
    driverService.Dispose();
}

Running 4 tests in parallel currently so want to avoid closing all browsers by accident.

Have confirmed the AfterScenario is being called when a scenario finishes but they still seem to be lurking and slowing down my machine locally when they stack up. As mentioned I have tried driver.Close() but this hasn't helped.

  • Chromeversion: 85.0.4183.8700
  • Specflow - 3.0.225
  • Selenium webdriver - 3.141

Since you already have a ChromeDriverService available, kill the process explicitly in your [AfterScenario] hook:

[AfterScenario]
public void AfterScenario()
{
    // Add a FeatureContext parameter to the class constructor if need be
    var driverService = featureContext.Get<ChromeDriverService>();
    var driver = _objectContainer.Resolve<IWebDriver>();

    try
    {
        if (driverService.ProcessId != default)
        {
            Trace.WriteLine("Attempting to kill web driver service process #" + driverService.ProcessId);

            var process = Process.GetByProcessId(driverService.ProcessId);

            process.Kill();
            Trace.WriteLine("   > Done killing process #" + driverService.ProcessId);
        }
    }
    catch (Exception ex)
    {
        Trace.WriteLine("Exception thrown when killing web driver service: " + ex);
    }

    try
    {
        driverService.Dispose();
        Trace.WriteLine("Web driver service disposed of.");
    }
    catch (Exception ex)
    {
        Trace.WriteLine("Exception thrown when disposing of web driver service: " + ex);
    }

    driver?.Close();
    driver?.Quit();
    driver?.Dispose();
}

Since Chrome 85, I've noticed that these ChromeDriver.exe processes are not cleaning up as easily as they were before. You would think the Dispose() method would kill the process, but lately I've had to add some extra strength cleanup and error handling.