多线程Selenium C#脚本CPU占满求助:Edge浏览器无法关闭
多线程Selenium C#下Edge浏览器无法关闭的问题解决思路
问题还原
多线程运行200个Selenium C#自动化脚本(线程数8),运行一段时间后CPU占用率达100%,核心原因是MsEdge浏览器进程无法正常关闭,耗尽系统内存。每个场景中调用Browser.Dispose()无效,报错信息如下:
Unable to connect to the remote server
Error Cannot start the driver service on http://localhost:
[ERROR] Exception has been thrown by the target of an invocation. -> Cannot start the driver service on http://localhost:
解决方案
1. 强制终止浏览器及驱动进程
仅调用Dispose()可能因连接异常导致进程残留,需显式杀死Edge主进程和驱动进程作为兜底:
// 优先执行正常关闭流程 try { driver.Quit(); // 必须用Quit()而非Close(),Quit会终止整个驱动会话 driver.Dispose(); } catch (Exception) { // 连接异常时直接杀进程 KillEdgeRelatedProcesses(); } // 自定义进程清理方法 private void KillEdgeRelatedProcesses() { // 终止msedgedriver驱动进程 foreach (var process in Process.GetProcessesByName("msedgedriver")) { try { process.Kill(); } catch { /* 忽略杀进程失败的情况 */ } } // 终止所有Edge浏览器进程(包括子进程) foreach (var process in Process.GetProcessesByName("msedge")) { try { process.Kill(); } catch { /* 忽略杀进程失败的情况 */ } } }
2. 确保线程独立的驱动实例管理
多线程环境下,每个线程必须持有独立的IWebDriver实例,绝对不能共享驱动对象:
- 禁止在静态类中存储驱动实例,避免跨线程引用导致资源无法释放
- 每个脚本/线程单独创建、使用、销毁EdgeDriver实例
3. 配置驱动服务的超时与自动清理
初始化EdgeDriver时,显式配置驱动服务参数,降低连接超时导致的进程残留概率:
var edgeOptions = new EdgeOptions(); // 可选:添加无头模式等配置减少资源占用 edgeOptions.AddArgument("--headless=new"); edgeOptions.AddArgument("--disable-gpu"); edgeOptions.AddArgument("--no-sandbox"); var driverService = EdgeDriverService.CreateDefaultService(); driverService.StartupTimeout = TimeSpan.FromSeconds(30); // 延长启动超时时间 driverService.HideCommandPromptWindow = true; var driver = new EdgeDriver(driverService, edgeOptions);
即使驱动启动失败,也要确保销毁驱动服务:
if (driverService != null && driverService.IsRunning) { try { driverService.Dispose(); } catch { } }
4. 全局异常捕获与兜底清理
在脚本执行的完整生命周期添加finally块,确保无论是否出现连接异常,都能执行资源清理:
IWebDriver driver = null; EdgeDriverService driverService = null; try { // 初始化驱动 driverService = EdgeDriverService.CreateDefaultService(); var options = new EdgeOptions(); driver = new EdgeDriver(driverService, options); // 执行自动化业务逻辑 // ... } catch (Exception ex) { // 记录错误日志 Console.WriteLine($"执行异常: {ex.Message}"); } finally { // 确保驱动正常销毁 if (driver != null) { try { driver.Quit(); } catch { } try { driver.Dispose(); } catch { } } // 确保驱动服务销毁 if (driverService != null) { try { driverService.Dispose(); } catch { } } // 兜底:强制清理残留进程 KillEdgeRelatedProcesses(); }
5. 优化线程数量与资源分配
8线程对应200个脚本,若每个脚本打开多窗口,可能超出系统资源承载上限:
- 适当降低线程数(如调整为4-6),减少资源竞争
- 若硬件允许,增加系统内存,提升多进程承载能力
内容的提问来源于stack exchange,提问作者Karthik KD
相关产品推荐
相关产品推荐

