以前在作爬蟲的時候,遇到內存釋放不掉的問題,從內存中釋放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