/// <summary>
        /// Runs the windows service that this instance was initialized with.
        /// This method is inteded to be run from the application's main thread and will block until the service has stopped.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Win32Exception">Thrown when an exception ocurrs when communicating with windows' service system.</exception>
        /// <exception cref="PlatformNotSupportedException">Thrown when run on a non-windows platform.</exception>
        public int Run()
        {
            var serviceTable = new ServiceTableEntry[2]; // second one is null/null to indicate termination

            serviceTable[0].serviceName         = serviceName;
            serviceTable[0].serviceMainFunction = Marshal.GetFunctionPointerForDelegate(serviceMainFunctionDelegate);

            try
            {
                // StartServiceCtrlDispatcherW call returns when ServiceMainFunction has exited and all services have stopped
                // at least this is what's documented even though linked c++ sample has an additional stop event
                // to let the service main function dispatched to block until the service stops.
                if (!nativeInterop.StartServiceCtrlDispatcherW(serviceTable))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            catch (DllNotFoundException dllException)
            {
                throw new PlatformNotSupportedException(nameof(Win32ServiceHost) + " is only supported on Windows with service management API set.",
                                                        dllException);
            }

            if (resultException != null)
            {
                throw resultException;
            }

            return(resultCode);
        }
Esempio n. 2
0
        public Task <int> RunAsync()
        {
            var serviceTable = new ServiceTableEntry[2];

            serviceTable[0].serviceName         = serviceName;
            serviceTable[0].serviceMainFunction = Marshal.GetFunctionPointerForDelegate(serviceMainFunctionDelegate);

            try
            {
                if (!nativeInterop.StartServiceCtrlDispatcherW(serviceTable))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            catch (DllNotFoundException dllException)
            {
                throw new PlatformNotSupportedException(nameof(Win32ServiceHost) + " is only supported on Windows with service management API set.",
                                                        dllException);
            }

            return(stopTaskCompletionSource.Task);
        }