ServiceBaseとは? わかりやすく解説

ServiceBase イベント


ServiceBase クラス

サービス アプリケーション一部として存在するサービス基本クラス提供しますServiceBase は、新しサービス クラス作成時に派生される必要があります

名前空間: System.ServiceProcess
アセンブリ: System.ServiceProcess (system.serviceprocess.dll 内)
構文構文

Public Class ServiceBase
    Inherits Component
public class ServiceBase : Component
public class ServiceBase extends Component
public class ServiceBase extends
 Component
解説解説

サービス アプリケーションサービス クラス定義するときに、ServiceBase から派生します。すべての有効なサービスが、OnStart メソッドと OnStop メソッドオーバーライドます。追加の機能については、サービス状態の変更応じた特定の動作で OnPause と OnContinue をオーバーライドできます

サービスは、ユーザー インターフェイスサポートしない、長期間実行できる実行可能ファイルです。ログオンしたユーザー アカウントによってはサービス実行できない場合ありますコンピュータログオンしているユーザーがいない場合でも、サービス実行できます

既定では、サービスシステム アカウント実行されます。このシステム アカウントは、管理者アカウントとは異なりますシステム アカウント権限変更できません。ただし、ServiceProcessInstaller を使用してサービス実行するときに使用するユーザー アカウント指定できます

実行可能ファイルには、複数サービス格納できますが、サービスごとに個別の ServiceInstaller を格納する必要がありますServiceInstaller インスタンスは、システムサービス登録しますまた、インストーラは、各サービスサービス コマンド記録するために使用できるイベント ログ関連付けます。実行可能ファイルmain() 関数は、実行するサービス定義しますサービス現在の作業ディレクトリは、実行可能ファイル置かれているディレクトリではなくシステム ディレクトリです。

サービス開始すると、実行可能ファイル検索され実行可能ファイル内にある該当サービスOnStart メソッド実行されます。ただし、実行可能ファイル実行しても、サービス実行されません。実行可能ファイルは、サービス読み込むだけです。サービスには、サービス コントロール マネージャ使用してアクセス (開始停止など) します。

実行可能ファイルは、サービス最初に Start呼び出すときに、ServiceBase 派生クラスコンストラクタ呼び出します。OnStart コマンド処理メソッドは、コンストラクタ実行され直後呼び出されます。コンストラクタは、サービス読み込まれ初回にしか実行されません。このためコンストラクタ実行される処理と OnStart実行される処理を区別する必要がありますOnStop によって解放できるリソースは、OnStart作成する必要がありますOnStopリソース解放した後にサービス再開すると、コンストラクタリソース作成して適切に作成されません。

サービス コントロール マネージャ (SCM: Service Control Manager) を使用すると、サービス対話形式利用できますSCM使用してStartStopPauseContinue の各コマンドまたはカスタム コマンドサービスに渡すことができますSCM は CanStop の値および CanPauseAndContinue の値を使用してサービスStopPause、または Continueいずれかコマンド受け入れかどうか判断しますStopPause、および Continue は、対応するプロパティである CanStop または CanPauseAndContinueサービス クラスtrue である場合限りSCMコンテキスト メニュー有効になります有効な場合コマンドサービス渡されOnStopOnPause、または OnContinue呼び出されます。CanStop、CanShutdown、または CanPauseAndContinuefalse場合は、対応するコマンド処理メソッド (OnStop など) を実装している場合でも、そのメソッド処理されません。

ServiceController クラス使用すると、ユーザー インターフェイスから SCM実行する処理をプログラムか実行できますコンソール実行するタスク自動化できますCanStopCanShutdown、または CanPauseAndContinuetrue で、OnStop などの対応するコマンド処理メソッド実装ていない場合システム例外スローし、コマンド無視します。

OnStartOnStop、または ServiceBase の他のメソッド実装する必要はありません。ただし、サービス動作OnStart記述されているため、最低限、このメンバオーバーライドされる必要があります実行可能ファイルmain() 関数サービス名設定する必要がありますmain()設定したサービス名は、サービス インストーラの ServiceName プロパティ完全に一致する必要があります

InstallUtil.exe使用してシステムサービスインストールできます

メモメモ

アプリケーション イベント ログ以外のログサービス呼び出し通知受け取るように指定できますが、AutoLog プロパティと EventLog プロパティいずれもカスタム ログへの書き込みができません。自動的にログ記録しない場合は、AutoLogfalse設定します

使用例使用例

簡単なサービス実装ServiceBase クラスから派生する例を次に示します。このサービスは、StopStartPauseContinueカスタム コマンドなどのさまざまなサービス コマンド処理します

// Turn on logging to the event log.
#define LOGEVENTS

using System;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace ServiceSample
{
    // Define custom commands for the SimpleService.
    public enum SimpleServiceCustomCommands { StopWorker = 128,
 RestartWorker, CheckWorker };
    [StructLayout(LayoutKind.Sequential)]
    public struct SERVICE_STATUS
    {
        public int serviceType;
        public int currentState;
        public int controlsAccepted;
        public int win32ExitCode;
        public int serviceSpecificExitCode;
        public int checkPoint;
        public int waitHint;
    }

    public enum State
    {
        SERVICE_STOPPED = 0x00000001,
        SERVICE_START_PENDING = 0x00000002,
        SERVICE_STOP_PENDING = 0x00000003,
        SERVICE_RUNNING = 0x00000004,
        SERVICE_CONTINUE_PENDING = 0x00000005,
        SERVICE_PAUSE_PENDING = 0x00000006,
        SERVICE_PAUSED = 0x00000007,
    }

    // Define a simple service implementation.
    public class SimpleService : System.ServiceProcess.ServiceBase
    {
        private static int
 userCount = 0;
        private static ManualResetEvent pause
 = new ManualResetEvent(false);

        [DllImport("ADVAPI32.DLL", EntryPoint = "SetServiceStatus")]
        public static extern bool
 SetServiceStatus(
                        IntPtr hServiceStatus,
                        SERVICE_STATUS lpServiceStatus
                        );
        private SERVICE_STATUS myServiceStatus;

        private Thread workerThread = null;

        public SimpleService()
        {
            CanPauseAndContinue = true;
            CanHandleSessionChangeEvent = true;
            ServiceName = "SimpleService";
        }

        static void Main()
        {
#if LOGEVENTS
            EventLog.WriteEntry("SimpleService.Main", DateTime.Now.ToLongTimeString()
 +
                " - Service main method starting...");
#endif

            // Load the service into memory.
            System.ServiceProcess.ServiceBase.Run(new SimpleService());

#if LOGEVENTS
            EventLog.WriteEntry("SimpleService.Main", DateTime.Now.ToLongTimeString()
 +
                " - Service main method exiting...");
#endif

        }

        private void InitializeComponent()
        {
            // Initialize the operating properties for the service.
            this.CanPauseAndContinue = true;
            this.CanShutdown = true;
            this.CanHandleSessionChangeEvent = true;
            this.ServiceName = "SimpleService";
        }

        // Start the service.
        protected override void OnStart(string[]
 args)
        {
            IntPtr handle = this.ServiceHandle;
            myServiceStatus.currentState = (int)State.SERVICE_START_PENDING;
            SetServiceStatus(handle, myServiceStatus);

            // Start a separate thread that does the actual work.

            if ((workerThread == null) ||
                ((workerThread.ThreadState &
                 (System.Threading.ThreadState.Unstarted | System.Threading.ThreadState.Stopped))
 != 0))
            {
#if LOGEVENTS
                EventLog.WriteEntry("SimpleService.OnStart", DateTime.Now.ToLongTimeString()
 +
                    " - Starting the service worker thread.");
#endif

                workerThread = new Thread(new
 ThreadStart(ServiceWorkerMethod));
                workerThread.Start();
            }
            if (workerThread != null)
            {
#if LOGEVENTS
                EventLog.WriteEntry("SimpleService.OnStart", DateTime.Now.ToLongTimeString()
 +
                    " - Worker thread state = " +
                    workerThread.ThreadState.ToString());
#endif
            }
            myServiceStatus.currentState = (int)State.SERVICE_RUNNING;
            SetServiceStatus(handle, myServiceStatus);

        }

        // Stop this service.
        protected override void OnStop()
        {
            // New in .NET Framework version 2.0.
            this.RequestAdditionalTime(4000);
            // Signal the worker thread to exit.
            if ((workerThread != null) &&
 (workerThread.IsAlive))
            {
#if LOGEVENTS
                EventLog.WriteEntry("SimpleService.OnStop", DateTime.Now.ToLongTimeString()
 +
                    " - Stopping the service worker thread.");
#endif
                pause.Reset();
                Thread.Sleep(5000);
                workerThread.Abort();

            }
            if (workerThread != null)
            {
#if LOGEVENTS
                EventLog.WriteEntry("SimpleService.OnStop", DateTime.Now.ToLongTimeString()
 +
                    " - OnStop Worker thread state = " +
                    workerThread.ThreadState.ToString());
#endif
            }
            // Indicate a successful exit.
            this.ExitCode = 0;
        }

        // Pause the service.
        protected override void OnPause()
        {
            // Pause the worker thread.
            if ((workerThread != null) &&
                (workerThread.IsAlive) &&
                ((workerThread.ThreadState &
                 (System.Threading.ThreadState.Suspended | System.Threading.ThreadState.SuspendRequested))
 == 0))
            {
#if LOGEVENTS
                EventLog.WriteEntry("SimpleService.OnPause", DateTime.Now.ToLongTimeString()
 +
                    " - Pausing the service worker thread.");
#endif

                pause.Reset();
                Thread.Sleep(5000);
            }

            if (workerThread != null)
            {
#if LOGEVENTS
                EventLog.WriteEntry("SimpleService.OnPause", DateTime.Now.ToLongTimeString()
 +
                    " OnPause - Worker thread state = " +
                    workerThread.ThreadState.ToString());
#endif
            }
        }

        // Continue a paused service.
        protected override void OnContinue()
        {

            // Signal the worker thread to continue.
            if ((workerThread != null) &&
                ((workerThread.ThreadState &
                 (System.Threading.ThreadState.Suspended | System.Threading.ThreadState.SuspendRequested))
 != 0))
            {
#if LOGEVENTS
                EventLog.WriteEntry("SimpleService.OnContinue", DateTime.Now.ToLongTimeString()
 +
                    " - Resuming the service worker thread.");

#endif
                pause.Set();
            }
            if (workerThread != null)
            {
#if LOGEVENTS
                EventLog.WriteEntry("SimpleService.OnContinue", DateTime.Now.ToLongTimeString()
 +
                    " OnContinue - Worker thread state = " +
                    workerThread.ThreadState.ToString());
#endif
            }
        }

        // Handle a custom command.
        protected override void OnCustomCommand(int
 command)
        {
#if LOGEVENTS
            EventLog.WriteEntry("SimpleService.OnCustomCommand", DateTime.Now.ToLongTimeString()
 +
                " - Custom command received: " +
                command.ToString());
#endif

            // If the custom command is recognized,
            // signal the worker thread appropriately.

            switch (command)
            {
                case (int)SimpleServiceCustomCommands.StopWorker:
                    // Signal the worker thread to terminate.
                    // For this custom command, the main service
                    // continues to run without a worker thread.
                    OnStop();
                    break;

                case (int)SimpleServiceCustomCommands.RestartWorker:

                    // Restart the worker thread if necessary.
                    OnStart(null);
                    break;

                case (int)SimpleServiceCustomCommands.CheckWorker:
#if LOGEVENTS
                    // Log the current worker thread state.
                    EventLog.WriteEntry("SimpleService.OnCustomCommand"
, DateTime.Now.ToLongTimeString()
 +
                        " OnCustomCommand - Worker thread state = " +
                        workerThread.ThreadState.ToString());
#endif

                    break;

                default:
#if LOGEVENTS
                    EventLog.WriteEntry("SimpleService.OnCustomCommand"
,
                        DateTime.Now.ToLongTimeString());
#endif
                    break;
            }
        }
        // Handle a session change notice
        protected override void OnSessionChange(SessionChangeDescription
 changeDescription)
        {
#if LOGEVENTS
            EventLog.WriteEntry("SimpleService.OnSessionChange", DateTime.Now.ToLongTimeString()
 +
                " - Session change notice received: " +
                changeDescription.Reason.ToString() + "  Session ID: "
 + 
                changeDescription.SessionId.ToString());
#endif

            switch (changeDescription.Reason)
            {
                case SessionChangeReason.SessionLogon:
                    userCount += 1;
#if LOGEVENTS
                    EventLog.WriteEntry("SimpleService.OnSessionChange",
 
                        DateTime.Now.ToLongTimeString() +
                        " SessionLogon, total users: " +
                        userCount.ToString());
#endif
                    break;

                case SessionChangeReason.SessionLogoff:

                    userCount -= 1;
#if LOGEVENTS
                    EventLog.WriteEntry("SimpleService.OnSessionChange",
 
                        DateTime.Now.ToLongTimeString() +
                        " SessionLogoff, total users: " +
                        userCount.ToString());
#endif
                    break;
                case SessionChangeReason.RemoteConnect:
                    userCount += 1;
#if LOGEVENTS
                    EventLog.WriteEntry("SimpleService.OnSessionChange",
 
                        DateTime.Now.ToLongTimeString() +
                        " RemoteConnect, total users: " +
                        userCount.ToString());
#endif
                    break;

                case SessionChangeReason.RemoteDisconnect:

                    userCount -= 1;
#if LOGEVENTS
                    EventLog.WriteEntry("SimpleService.OnSessionChange",
 
                        DateTime.Now.ToLongTimeString() +
                        " RemoteDisconnect, total users: " +
                        userCount.ToString());
#endif
                    break;
                case SessionChangeReason.SessionLock:
#if LOGEVENTS
                    EventLog.WriteEntry("SimpleService.OnSessionChange",
 
                        DateTime.Now.ToLongTimeString() + 
                        " SessionLock");
#endif
                    break;

                case SessionChangeReason.SessionUnlock:
#if LOGEVENTS
                    EventLog.WriteEntry("SimpleService.OnSessionChange",
 
                        DateTime.Now.ToLongTimeString() + 
                        " SessionUnlock");
#endif
                    break;

                default:

                    break;
            }
        }
        // Define a simple method that runs as the worker thread for
 
        // the service.  
        public void ServiceWorkerMethod()
        {
#if LOGEVENTS
            EventLog.WriteEntry("SimpleService.WorkerThread", DateTime.Now.ToLongTimeString()
 +
                " - Starting the service worker thread.");
#endif

            try
            {
                do
                {
                    // Simulate 4 seconds of work.
                    Thread.Sleep(4000);
                    // Block if the service is paused or is shutting
 down.
                    pause.WaitOne();
#if LOGEVENTS
                    EventLog.WriteEntry("SimpleService.WorkerThread", DateTime.Now.ToLongTimeString()
 +
                        " - heartbeat cycle.");
#endif
                }
                while (true);
            }
            catch (ThreadAbortException)
            {
                // Another thread has signalled that this worker
                // thread must terminate.  Typically, this occurs when
                // the main service thread receives a service stop 
                // command.

                // Write a trace line indicating that the worker thread
                // is exiting.  Notice that this simple thread does
                // not have any local objects or data to clean up.
#if LOGEVENTS
                EventLog.WriteEntry("SimpleService.WorkerThread", DateTime.Now.ToLongTimeString()
 +
                    " - Thread abort signaled.");
#endif
            }
#if LOGEVENTS

            EventLog.WriteEntry("SimpleService.WorkerThread", DateTime.Now.ToLongTimeString()
 +
                " - Exiting the service worker thread.");
#endif

        }
    }
}
// Turn on the constant for trace output.
#define TRACE

#using <System.ServiceProcess.dll>
#using <System.dll>

using namespace System;
using namespace System::ComponentModel;
using namespace System::IO;
using namespace System::ServiceProcess;
using namespace System::Threading;
using namespace System::Diagnostics;

// Define custom commands for the SimpleService.
public enum class SimpleServiceCustomCommands
{
    StopWorker = 128,
    RestartWorker, CheckWorker
};


// Define a simple service implementation.
public ref class SimpleService: public
 System::ServiceProcess::ServiceBase
{
private:
    Thread^ workerThread;
    int userCount;
public:
    SimpleService()
    {
        CanPauseAndContinue = true;
        ServiceName = "SimpleService";
        workerThread = nullptr;
        CanHandleSessionChangeEvent = true;
    }

private:

    void InitializeComponent()
    {
        // Initialize the operating properties for the service.
        this->CanPauseAndContinue = true;
        this->CanShutdown = true;
        this->ServiceName = "SimpleService";
        this->CanHandleSessionChangeEvent = true;
    }

    // Start the service.
protected:
    virtual void OnStart( array<String^>^  ) override
    {
        // Start a separate thread that does the actual work.
        if ( (workerThread == nullptr) || ((workerThread->ThreadState
 & (System::Threading::ThreadState::Unstarted | System::Threading::ThreadState::Stopped))
 != (System::Threading::ThreadState)0) )
        {
            Trace::WriteLine( DateTime::Now.ToLongTimeString() + " - Starting
 the service worker thread.", "OnStart" );
            workerThread = gcnew Thread( gcnew ThreadStart( this,&SimpleService::ServiceWorkerMethod
 ) );
            workerThread->Start();
        }

        if ( workerThread != nullptr )
        {
            Trace::WriteLine( DateTime::Now.ToLongTimeString() + " - Worker
 thread state = " + workerThread->ThreadState.ToString(), "OnStart"
 );
        }
    }

    // Stop this service.
protected:
    virtual void OnStop() override
    {
        // Signal the worker thread to exit.
        if ( (workerThread != nullptr) && (workerThread->IsAlive)
 )
        {
            Trace::WriteLine( DateTime::Now.ToLongTimeString() + " - Stopping
 the service worker thread.", "OnStop" );
            workerThread->Abort();

            // Wait up to 500 milliseconds for the thread to terminate.
            workerThread->Join( 500 );
        }

        if ( workerThread != nullptr )
        {
            Trace::WriteLine( DateTime::Now.ToLongTimeString() + " - Worker
 thread state = " + workerThread->ThreadState.ToString(), "OnStop"
 );
        }
    }

    // Pause the service.
protected:
    virtual void OnPause() override
    {
        // Pause the worker thread.
        if ( (workerThread != nullptr) && (workerThread->IsAlive)
 && ((workerThread->ThreadState & (System::Threading::ThreadState::Suspended
 | System::Threading::ThreadState::SuspendRequested)) == (System::Threading::ThreadState)0) )
        {
            Trace::WriteLine( DateTime::Now.ToLongTimeString() + " - Suspending
 the service worker thread.", "OnPause" );
            workerThread->Suspend();
        }

        if ( workerThread != nullptr )
        {
            Trace::WriteLine( DateTime::Now.ToLongTimeString() + " - Worker
 thread state = " + workerThread->ThreadState.ToString(), "OnPause"
 );
        }
    }

    // Continue a paused service.
protected:
    virtual void OnContinue() override
    {
        // Signal the worker thread to continue.
        if ( (workerThread != nullptr) && ((workerThread->ThreadState
 & (System::Threading::ThreadState::Suspended | System::Threading::ThreadState::SuspendRequested))
 != (System::Threading::ThreadState)0) )
        {
            Trace::WriteLine( DateTime::Now.ToLongTimeString() + " - Resuming
 the service worker thread.", "OnContinue" );
            workerThread->Resume();
        }

        if ( workerThread != nullptr )
        {
            Trace::WriteLine( DateTime::Now.ToLongTimeString() + " - Worker
 thread state = " + workerThread->ThreadState.ToString(), "OnContinue"
 );
        }
    }

    // Handle a custom command.
protected:
    virtual void OnCustomCommand( int command
 ) override
    {
        Trace::WriteLine( DateTime::Now.ToLongTimeString() + " - Custom command
 received: " + command, "OnCustomCommand" );

        // If the custom command is recognized,
        // signal the worker thread appropriately.
        switch ( command )
        {
        case (int)SimpleServiceCustomCommands::StopWorker:

            // Signal the worker thread to terminate.
            // For this custom command, the main service
            // continues to run without a worker thread.
            OnStop();
            break;

        case (int)SimpleServiceCustomCommands::RestartWorker:

            // Restart the worker thread if necessary.
            OnStart( nullptr );
            break;

        case (int)SimpleServiceCustomCommands::CheckWorker:

            // Log the current worker thread state.
            Trace::WriteLine( DateTime::Now.ToLongTimeString() + " - Worker
 thread state = " + workerThread->ThreadState.ToString(), "OnCustomCommand"
 );
            break;

        default:
            Trace::WriteLine( DateTime::Now.ToLongTimeString() + " - Unrecognized
 custom command ignored!", "OnCustomCommand" );
            break;
        }
    }
protected:
    virtual void OnSessionChange(SessionChangeDescription changeDescription)
 override
    {
        Trace::WriteLine( DateTime::Now.ToLongTimeString() + " - Change description
 received: " 
            + changeDescription.ToString(), "OnSessionChange" );

        switch (changeDescription.Reason)
        {
        case SessionChangeReason::SessionLogon:
            userCount += 1;
            Trace::WriteLine( DateTime::Now.ToLongTimeString() + 
                " SessionLogon, total users: " + 
                userCount.ToString(), "OnSessionChange" );
            break;
        case SessionChangeReason::SessionLogoff:
            userCount -= 1;
            Trace::WriteLine( DateTime::Now.ToLongTimeString() + 
                " SessionLogoff, total users: " + 
                userCount.ToString(), "OnSessionChange" );
            break;
        case SessionChangeReason::RemoteConnect:
            userCount += 1;
            Trace::WriteLine( DateTime::Now.ToLongTimeString() + 
                " RemoteConnect, total users: " + 
                userCount.ToString(), "OnSessionChange" );
            break;
        case SessionChangeReason::RemoteDisconnect:
            userCount -= 1;
            Trace::WriteLine( DateTime::Now.ToLongTimeString() + 
                " RemoteDisconnect, total users: " + 
                userCount.ToString(), "OnSessionChange" );
            break;
        case SessionChangeReason::SessionLock:
            Trace::WriteLine( DateTime::Now.ToLongTimeString() + 
                " SessionLock", "OnSessionChange" );
            break;
        case SessionChangeReason::SessionUnlock:
            Trace::WriteLine( DateTime::Now.ToLongTimeString() + 
                " SessionUnlock", "OnSessionChange" );
            break;

        default:
            Trace::WriteLine( DateTime::Now.ToLongTimeString() + 
                " - Unhandled session change event.", "OnSessionChange"
 );
            break;
        }
    }
    // Define a simple method that runs as the worker thread for 
    // the service.  
public:
    void ServiceWorkerMethod()
    {
        Trace::WriteLine( DateTime::Now.ToLongTimeString() + " - Starting the
 service worker thread.", "Worker" );
        try
        {
            for ( ; ;  )
            {

                // Wake up every 10 seconds and write
                // a message to the trace output.
                Thread::Sleep( 10000 );
                Trace::WriteLine( DateTime::Now.ToLongTimeString() + " - heartbeat
 cycle.", "Worker" );
            }
        }
        catch ( ThreadAbortException^ ) 
        {
            // Another thread has signalled that this worker
            // thread must terminate.  Typically, this occurs when
            // the main service thread receives a service stop 
            // command.
            // Write a trace line indicating that the worker thread
            // is exiting.  Notice that this simple thread does
            // not have any local objects or data to clean up.
            Trace::WriteLine( DateTime::Now.ToLongTimeString() + " - Thread
 abort signaled.", "Worker" );
        }

        Trace::WriteLine( DateTime::Now.ToLongTimeString() + " - Exiting the
 service worker thread.", "Worker" );
    }
};

int main()
{
    String^ logFile = "C:\\service_log.txt";
    TextWriterTraceListener^ serviceTraceListener = nullptr;

    // Create a log file for trace output.
    // A new file is created each time.  If a
    // previous log file exists, it is overwritten.
    StreamWriter^ myFile = File::CreateText( logFile );

    // Create a new trace listener that writes to the text file,
    // and add it to the collection of trace listeners.
    serviceTraceListener = gcnew TextWriterTraceListener( myFile );
    Trace::Listeners->Add( serviceTraceListener );
    Trace::AutoFlush = true;
    Trace::WriteLine( DateTime::Now.ToLongTimeString() + " - Service main method
 starting...", "Main" );

    // Load the service into memory.
    System::ServiceProcess::ServiceBase::Run( gcnew SimpleService );
    Trace::WriteLine( DateTime::Now.ToLongTimeString() + " - Service main method
 exiting...", "Main" );

    // Remove and close the trace listener for this service.
    Trace::Listeners->Remove( serviceTraceListener );
    serviceTraceListener->Close();
    serviceTraceListener = nullptr;
    myFile->Close();
}
継承階層継承階層
System.Object
   System.MarshalByRefObject
     System.ComponentModel.Component
      System.ServiceProcess.ServiceBase
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
ServiceBase メンバ
System.ServiceProcess 名前空間
ServiceProcessInstaller
ServiceInstaller

ServiceBase コンストラクタ

ServiceBase クラス新しインスタンス作成します

名前空間: System.ServiceProcess
アセンブリ: System.ServiceProcess (system.serviceprocess.dll 内)
構文構文

public ServiceBase ()
public:
ServiceBase ()
public ServiceBase ()
解説解説

ServiceBase クラスインスタンス作成しないください代わりにServiceBase から派生させて、派生クラスインスタンス化ます。ServiceBase から継承されクラスコンストラクタ実装するためには、最低限コンポーネントで ServiceName を設定する必要がありますその他の特別な処理をコンストラクタで行う必要はありません。ほとんどの初期化は、コンストラクタではなく OnStart で処理する必要がありますコンストラクタ処理すると、サービス停止してから再開するときに、オブジェクトが再初期化されない場合あります

派生クラスコンストラクタオーバーライドする場合は、コード内で基本クラスコンストラクタ呼び出します。

ServiceBase コンストラクタは、AutoLog を true設定しますサービス コントロール マネージャ (SCM) からのサービス呼び出し自動的にログ記録しない場合は、AutoLogfalse設定します

実行可能ファイルサービス1 つだけ含まれている場合は、SCMStart選択されるサービスコンストラクタ呼び出されStop呼び出されるデストラクタ実行されます。

実行可能ファイル複数サービス含まれる場合は、1 つサービスStart呼び出されると、実行可能ファイル内のすべてのサービスコンストラクタ呼び出されますが、開始されるのは指定されサービスだけです。サービスデストラクタは、各サービス個別停止したときではなくすべてのサービス停止したときに一度実行されます。

メモメモ

基本クラスコンストラクタオーバーライドする場合は、派生クラスコンストラクタ基本クラス明示的に呼び出す必要があります

使用例使用例

ServiceBase から派生したサービス クラスコンストラクタの例を次に示します。このコード例は、ServiceBase クラストピック取り上げているコード例一部分です。

Public Sub New()
    CanPauseAndContinue = True
    CanHandleSessionChangeEvent = True
    ServiceName = "SimpleService"

End Sub 'New

public SimpleService()
{
    CanPauseAndContinue = true;
    CanHandleSessionChangeEvent = true;
    ServiceName = "SimpleService";
}
public:
    SimpleService()
    {
        CanPauseAndContinue = true;
        ServiceName = "SimpleService";
        workerThread = nullptr;
        CanHandleSessionChangeEvent = true;
    }
.NET Framework のセキュリティ.NET Frameworkセキュリティ
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

ServiceBase フィールド


パブリック フィールドパブリック フィールド

  名前 説明
パブリック フィールド MaxNameLength サービス名最大サイズ示します
参照参照

関連項目

ServiceBase クラス
System.ServiceProcess 名前空間
ServiceProcessInstaller
ServiceInstaller

ServiceBase プロパティ


パブリック プロパティパブリック プロパティ

( プロテクト プロパティ参照)
  名前 説明
パブリック プロパティ AutoLog イベント ログで、StartStopPauseContinue の各コマンドレポートするかどうか示します
パブリック プロパティ CanHandlePowerEvent サービスで、コンピュータ電源ステータス変更通知処理できるかどうかを示す値を取得または設定します
パブリック プロパティ CanHandleSessionChangeEvent ターミナル サーバー セッションから受信したセッション変更イベントサービス処理できるかどうかを示す値を取得または設定します
パブリック プロパティ CanPauseAndContinue サービス一時中断および再開できるかどうかを示す値を取得または設定します
パブリック プロパティ CanShutdown システムシャットダウン時にサービスにそれを通知する必要があるかどうかを示す値を取得または設定します
パブリック プロパティ CanStop サービス開始した後に停止できるかどうかを示す値を取得または設定します
パブリック プロパティ Container  Component格納している IContainer を取得します。 ( Component から継承されます。)
パブリック プロパティ EventLog StartStop などのサービス コマンド呼び出し通知アプリケーション イベント ログ書き込むために使用できるイベント ログ取得します
パブリック プロパティ ExitCode サービスの終了コード取得または設定します
パブリック プロパティ ServiceName システムサービス識別するために使用される短い名前を取得または設定します
パブリック プロパティ Site  Component の ISite を取得または設定します。 ( Component から継承されます。)
プロテクト プロパティプロテクト プロパティ
参照参照

関連項目

ServiceBase クラス
System.ServiceProcess 名前空間
ServiceProcessInstaller
ServiceInstaller

ServiceBase メソッド


パブリック メソッドパブリック メソッド

( プロテクト メソッド参照)
  名前 説明
パブリック メソッド CreateObjRef  リモート オブジェクトとの通信使用するプロキシ生成必要な情報をすべて格納しているオブジェクト作成します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド Dispose オーバーロードされます。 ServiceBase によって使用されているリソース破棄します。
パブリック メソッド Equals  オーバーロードされます2 つObject インスタンス等しかどうか判断します。 ( Object から継承されます。)
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用適してます。 ( Object から継承されます。)
パブリック メソッド GetLifetimeService  対象インスタンス有効期間ポリシー制御する現在の有効期間サービス オブジェクト取得します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド GetType  現在のインスタンスType取得します。 ( Object から継承されます。)
パブリック メソッド InitializeLifetimeService  対象インスタンス有効期間ポリシー制御する有効期間サービス オブジェクト取得します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド ReferenceEquals  指定した複数Object インスタンス同一かどうか判断します。 ( Object から継承されます。)
パブリック メソッド RequestAdditionalTime 保留中の操作について時間延長要求します
パブリック メソッド Run オーバーロードされますサービス実行可能ファイルメイン エントリ ポイント示します
パブリック メソッド ServiceMainCallback コマンド ハンドラ登録しサービス開始します
パブリック メソッド Stop サービス実行停止します
パブリック メソッド ToString  Component の名前を格納している String返します (存在する場合)。このメソッドオーバーライドできません。 ( Component から継承されます。)
プロテクト メソッドプロテクト メソッド
  名前 説明
プロテクト メソッド Dispose オーバーロードされますオーバーライドされますServiceBase によって使用されているリソース破棄します。
プロテクト メソッド Finalize  Componentガベージ コレクションによってクリアされる前に、アンマネージ リソース解放しその他のクリーンアップ操作実行します。 ( Component から継承されます。)
プロテクト メソッド GetService  Component またはその Container提供されるサービスを表すオブジェクト返します。 ( Component から継承されます。)
プロテクト メソッド MemberwiseClone  オーバーロードされます。 ( MarshalByRefObject から継承されます。)
プロテクト メソッド OnContinue 派生クラス実装されると、OnContinue は、サービス コントロール マネージャ (SCM) によって Continue コマンドサービス送信されるときに実行されます。サービス一時中断してから通常の操作再開時に実行されるアクション指定します
プロテクト メソッド OnCustomCommand 派生クラス実装されると、OnCustomCommand は、サービス コントロール マネージャ (SCM) でカスタム コマンドサービス渡されるときに、実行されます。パラメータ値が設定されているコマンド発生時に実行されるアクション指定します
プロテクト メソッド OnPause 派生クラス実装されると、Pause コマンドサービス コントロール マネージャ (SCM) によってサービス送信されるときに実行されます。サービス一時中断したときに実行されるアクション指定します
プロテクト メソッド OnPowerEvent 派生クラス実装されると、コンピュータ電源ステータス変更時に実行されます。これは中断モードラップトップ コンピュータ適用されるもので、システムシャットダウンとは異なります
プロテクト メソッド OnSessionChange 変更イベントターミナル サーバー セッションから受信され場合実行します
プロテクト メソッド OnShutdown 派生クラス実装されると、システムシャット ダウンされるときに実行されます。システムシャット ダウンする直前発生する動作指定します
プロテクト メソッド OnStart 派生クラス実装されると、Start コマンドサービス コントロール マネージャ (SCM) によってサービス送信されるとき、またはオペレーティング システムが (自動的に起動するサービスのために) 起動するときに実行されます。サービス開始するときに実行されるアクション指定します
プロテクト メソッド OnStop 派生クラス実装されると、Stop コマンドサービス コントロール マネージャ (SCM) によってサービス送信されるときに実行されます。サービス実行停止したときに実行されるアクション指定します
参照参照

関連項目

ServiceBase クラス
System.ServiceProcess 名前空間
ServiceProcessInstaller
ServiceInstaller

ServiceBase メンバ

サービス アプリケーション一部として存在するサービス基本クラス提供します。ServiceBase は、新しサービス クラス作成時に派生される必要があります

ServiceBase データ型公開されるメンバを以下の表に示します


パブリック コンストラクタパブリック コンストラクタ
  名前 説明
パブリック メソッド ServiceBase ServiceBase クラス新しインスタンス作成します
パブリック フィールドパブリック フィールド
  名前 説明
パブリック フィールド MaxNameLength サービス名最大サイズ示します
パブリック プロパティパブリック プロパティ
( プロテクト プロパティ参照)
  名前 説明
パブリック プロパティ AutoLog イベント ログで、StartStopPauseContinue の各コマンドレポートするかどうか示します
パブリック プロパティ CanHandlePowerEvent サービスで、コンピュータ電源ステータス変更通知処理できるかどうかを示す値を取得または設定します
パブリック プロパティ CanHandleSessionChangeEvent ターミナル サーバー セッションから受信したセッション変更イベントサービス処理できるかどうかを示す値を取得または設定します
パブリック プロパティ CanPauseAndContinue サービス一時中断および再開できるかどうかを示す値を取得または設定します
パブリック プロパティ CanShutdown システムシャットダウン時にサービスにそれを通知する必要があるかどうかを示す値を取得または設定します
パブリック プロパティ CanStop サービス開始した後に停止できるかどうかを示す値を取得または設定します
パブリック プロパティ Container  Component格納している IContainer を取得します。(Component から継承されます。)
パブリック プロパティ EventLog StartStop などのサービス コマンド呼び出し通知アプリケーション イベント ログ書き込むために使用できるイベント ログ取得します
パブリック プロパティ ExitCode サービスの終了コード取得または設定します
パブリック プロパティ ServiceName システムサービス識別するために使用される短い名前を取得または設定します
パブリック プロパティ Site  Component の ISite を取得または設定します。(Component から継承されます。)
プロテクト プロパティプロテクト プロパティ
パブリック メソッドパブリック メソッド
( プロテクト メソッド参照)
  名前 説明
パブリック メソッド CreateObjRef  リモート オブジェクトとの通信使用するプロキシ生成必要な情報をすべて格納しているオブジェクト作成します。 (MarshalByRefObject から継承されます。)
パブリック メソッド Dispose オーバーロードされますServiceBase によって使用されているリソース破棄します。
パブリック メソッド Equals  オーバーロードされます2 つObject インスタンス等しかどうか判断します。 (Object から継承されます。)
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用適してます。 (Object から継承されます。)
パブリック メソッド GetLifetimeService  対象インスタンス有効期間ポリシー制御する現在の有効期間サービス オブジェクト取得します。 (MarshalByRefObject から継承されます。)
パブリック メソッド GetType  現在のインスタンスType取得します。 (Object から継承されます。)
パブリック メソッド InitializeLifetimeService  対象インスタンス有効期間ポリシー制御する有効期間サービス オブジェクト取得します。 (MarshalByRefObject から継承されます。)
パブリック メソッド ReferenceEquals  指定した複数Object インスタンス同一かどうか判断します。 (Object から継承されます。)
パブリック メソッド RequestAdditionalTime 保留中の操作について時間延長要求します
パブリック メソッド Run オーバーロードされますサービス実行可能ファイルメイン エントリ ポイント示します
パブリック メソッド ServiceMainCallback コマンド ハンドラ登録しサービス開始します
パブリック メソッド Stop サービス実行停止します
パブリック メソッド ToString  Component の名前を格納している String返します (存在する場合)。このメソッドオーバーライドできません。 (Component から継承されます。)
プロテクト メソッドプロテクト メソッド
  名前 説明
プロテクト メソッド Dispose オーバーロードされますオーバーライドされますServiceBase によって使用されているリソース破棄します。
プロテクト メソッド Finalize  Componentガベージ コレクションによってクリアされる前に、アンマネージ リソース解放しその他のクリーンアップ操作実行します。 (Component から継承されます。)
プロテクト メソッド GetService  Component またはその Container提供されるサービスを表すオブジェクト返します。 (Component から継承されます。)
プロテクト メソッド MemberwiseClone  オーバーロードされます。 ( MarshalByRefObject から継承されます。)
プロテクト メソッド OnContinue 派生クラス実装されると、OnContinue は、サービス コントロール マネージャ (SCM) によって Continue コマンドサービス送信されるときに実行されます。サービス一時中断してから通常の操作再開時に実行されるアクション指定します
プロテクト メソッド OnCustomCommand 派生クラス実装されると、OnCustomCommand は、サービス コントロール マネージャ (SCM) でカスタム コマンドサービス渡されるときに、実行されます。パラメータ値が設定されているコマンド発生時に実行されるアクション指定します
プロテクト メソッド OnPause 派生クラス実装されると、Pause コマンドサービス コントロール マネージャ (SCM) によってサービス送信されるときに実行されます。サービス一時中断したときに実行されるアクション指定します
プロテクト メソッド OnPowerEvent 派生クラス実装されると、コンピュータ電源ステータス変更時に実行されます。これは中断モードラップトップ コンピュータ適用されるもので、システムシャットダウンとは異なります
プロテクト メソッド OnSessionChange 変更イベントターミナル サーバー セッションから受信され場合実行します
プロテクト メソッド OnShutdown 派生クラス実装されると、システムシャット ダウンされるときに実行されます。システムシャット ダウンする直前発生する動作指定します
プロテクト メソッド OnStart 派生クラス実装されると、Start コマンドサービス コントロール マネージャ (SCM) によってサービス送信されるとき、またはオペレーティング システムが (自動的に起動するサービスのために) 起動するときに実行されます。サービス開始するときに実行されるアクション指定します
プロテクト メソッド OnStop 派生クラス実装されると、Stop コマンドサービス コントロール マネージャ (SCM) によってサービス送信されるときに実行されます。サービス実行停止したときに実行されるアクション指定します
パブリック イベントパブリック イベント
参照参照

関連項目

ServiceBase クラス
System.ServiceProcess 名前空間
ServiceProcessInstaller
ServiceInstaller



英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「ServiceBase」の関連用語

ServiceBaseのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



ServiceBaseのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2025 Microsoft.All rights reserved.

©2025 GRAS Group, Inc.RSS