SoFunction
Updated on 2025-03-07

c# Free Selenium from memory

background

I set up a c# code to run Selenium. At the end of the run, I have() to close the instance. (browser = ()) I believe it should be freed from memory (I'm on Windows 7). But after each run, there is still an instance in memory.

Peeping into the problem

In theory, the call will close all browser tabs and terminate the process.

However, in my case, I can't do this - because I run multiple tests in parallel, I don't want to do one test to close the other's window. So when my tests are finished running, there are still many "' processes running.

Solution

public override void DoJob(IJobExecutionContext context, ILifetimeScope scope, string[] args)
    {
      (nameof(LoginReptiles1688Job) + " start-------------------");
      ChromeOptions options = null;
      IWebDriver driver = null;
      try
      {
        options = new ChromeOptions();
        ("--ignore-certificate-errors");
        ("--ignore-ssl-errors");
        var listCookie = ();
        if (listCookie != null)
        {
          // ("headless");
        }
        ChromeDriverService service = ();
         = true;
        driver = new ChromeDriver(service, options, (120));
        var setLoginStatus = <ISetLoginStatus>();
        IReptilesImageSearchService _reptilesImageSearchService = <IReptilesImageSearchService>();
        CrawlingWeb(_reptilesImageSearchService, driver);
        CrawlingWebShop(_reptilesImageSearchService, driver);
      }
      catch (Exception ex)
      {
        throw ex;
      }
      finally
      {
        driver?.Close(); // Close the chrome window
        driver?.Quit(); // Close the console app that was used to kick off the chrome window
        driver?.Dispose(); // Close the 

        driver = null;
        options = null;
        detailtry = 0;
        shoptry = 0;
        (nameof(LoginReptiles1688Job) + " Finish-------------------");
      }
    }

The chrome driver is used in the C# console application and the delayed process can only be cleaned after all three methods are called together.

The above is the detailed content of C# to release Selenium from memory. For more information about releasing Selenium in memory, please follow my other related articles!