以前在作爬虫的时候,遇到内存释放不掉的问题,从内存中释放Selenium chromedriver.exe。后面我使用如下方法:chrome
public override void DoJob(IJobExecutionConxt context, ILifetimeScope scope, string[] args) { Console.WriteLine(nameof(LoginReptiles1688Job) + " 开始-------------------"); ChromeOptions options = null; IWebDriver driver = null; try { 。。。。。。。。。。。。。。。。。。。。。。。 } 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 chromedriver.exe driver = null; options = null; detailtry = 0; shoptry = 0; Console.WriteLine(nameof(LoginReptiles1688Job) + " 结束-------------------"); } }
这不,还真降下来了;可是,没等几天服务器又报警了,仍是老问题,后面捣鼓了半天,仍是没有解决问题。服务器
其实问题的根本缘由是Selenium chromedriver.exe无法正常关闭,虽然尝试了不少方法,可是始终无法测底解决;后面灵机一闪,何不来个完全点的,使用kill把整个chromedriver.exe线程干掉,这不就完全了;说干就干。app
#region 异常 退出chromedriver [DllImport("user32.dll", EntryPoint = "FindWindow")] private extern static IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll", EntryPoint = "SendMessage")] public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); public const int SW_HIDE = 0; public const int SW_SHOW = 5; [DllImport("user32.dll", EntryPoint = "ShowWindow")] public static extern int ShowWindow(IntPtr hwnd, int nCmdShow); /// <summary> /// 获取窗口句柄 /// </summary> /// <returns></returns> public IntPtr GetWindowHandle() { string name = (Environment.CurrentDirectory + "\\chromedriver.exe"); IntPtr hwd = FindWindow(null, name); return hwd; } /// <summary> /// 关闭chromedriver窗口 /// </summary> public void CloseWindow() { try { IntPtr hwd = GetWindowHandle(); SendMessage(hwd, 0x10, 0, 0); } catch { } } /// <summary> /// 退出chromedriver /// </summary> /// <param name="driver"></param> public void CloseChromeDriver(IWebDriver driver) { try { driver.Quit(); driver.Dispose(); } catch { } CloseWindow(); } #endregion 异常 退出chromedriver
一、果真够完全的,chromedriver.exe每次都正常关闭了,内存占用也正常。编辑器
二、事有两面性,有时候反方向来解决问题何尝不是一个好的办法。ide
三、使用这种方式,等于kill掉整个进程,因此不适合多个线程操做,不然会出 现中断的状况。ui