Asp.net
每當重新載入應用程序域時,如何強制 IIS 應用程序池重新啟動?
我們有一個連結到舊本機程式碼的 ASP.NET MVC 4 應用程序。問題是這個遺留程式碼具有在啟動時建構的全域靜態,但由於本機程式碼對應用程序域一無所知,因此在重新載入應用程序域時,該程式碼不會重新初始化。這會導致我們的應用程序出現錯誤行為或崩潰,直到重新啟動應用程序池程序。
因此,每當我們的應用程序的應用程序域被回收時,我想強制應用程序池進行回收。IIS 中是否有此設置,或者在解除安裝域時我可以在我的應用程序中呼叫程式碼嗎?
關於我的設置的一些資訊,
- ASP.NET MVC 4 應用程序
- IIS 7.5,但如果需要我可以移動到 8
- 我可以確保每個應用程序池有一個應用程序,因此我不會影響其他應用程序。
更新
根據下面的答案,我連接了 AppDomain 解除安裝事件並使用類似於以下的程式碼來回收應用程序池。
try { // Find the worker process running us and from that our AppPool int pid = Process.GetCurrentProcess().Id; var manager = new ServerManager(); WorkerProcess process = (from p in manager.WorkerProcesses where p.ProcessId == pid select p).FirstOrDefault(); // From the name, find the AppPool and recycle it if ( process != null ) { ApplicationPool pool = (from p in manager.ApplicationPools where p.Name == process.AppPoolName select p).FirstOrDefault(); if ( pool != null ) { log.Info( "Recycling Application Pool " + pool.Name ); pool.Recycle(); } } } catch ( NotImplementedException nie ) { log.InfoException( "Server Management functions are not implemented. We are likely running under IIS Express. Shutting down server.", nie ); Environment.Exit( 0 ); }
更殘忍的方法是呼叫 Process.GetCurrentProcess().Kill() 不是很優雅,但是如果你的站點有自己的應用程序池並且你不在乎任何目前的請求被殘忍地停止,那是相當有效的!
您共享的程式碼的簡化 VB 版本。此版本使用 For 循環而不是 LINQ 查詢。此外,為了使用 Microsoft.Web.Administration,您必須從 c:\windows\system32\inetsrv 導入 DLL
Imports System.Diagnostics Imports Microsoft.Web.Administration Dim pid As Integer = Process.GetCurrentProcess().Id Dim manager = New ServerManager() For Each p As WorkerProcess In manager.WorkerProcesses If p.ProcessId = pid Then For Each a As ApplicationPool In manager.ApplicationPools If a.Name = p.AppPoolName Then a.Recycle() Exit For End If Next Exit For End If Next