ServiceBase.OnStop 方法


在衍生類別中實作時,當服務控制管理員 (SCM) 傳送停止命令至服務時執行。When implemented in a derived class, executes when a Stop command is sent to the service by the Service Control Manager (SCM). 指定在服務停止執行時所要執行的動作。Specifies actions to take when a service stops running.

 virtual void OnStop();
protected virtual void OnStop ();
abstract member OnStop : unit -> unit
override this.OnStop : unit -> unit
Protected Overridable Sub OnStop ()


使用OnStop來指定服務收到停止命令時所發生的處理。Use OnStop to specify the processing that occurs when the service receives a Stop command.

當 SCM 收到 stop 命令時,它會使用的值CanStop來驗證服務是否接受 stop 命令。When the SCM receives a Stop command, it uses the value of CanStop to verify whether the service accepts Stop commands. 如果CanStop OnStoptrue,則會將 Stop 命令傳遞給服務,並在定義方法時呼叫它。If CanStop is true, the Stop command is passed to the service, and the OnStop method is called if it is defined. 如果OnStop未在服務中執行,SCM 會處理 Stop 命令。If OnStop is not implemented in the service, the SCM handles the Stop command.

如果CanStopfalse,則 SCM 會忽略 Stop 命令。If CanStop is false, the SCM ignores the Stop command. 它不會傳遞至服務。It is not passed to the service. Stop 命令會傳回,並擲回例外狀況。The Stop command returns and throws an exception.

OnStop應該在衍生類別中覆寫。OnStop is expected to be overridden in the derived class. 服務會很有用, OnStart而且OnStop應該同時在您的服務類別中執行。For the service to be useful, OnStart and OnStop should both be implemented in your service class.