static public void Unsubscribe()
 {
     lock (instanceContext)
     {
         try
         {
             _this?.Unsubscribe();
         }
         catch (Exception e)
         {
             Log.Main.Warning2(e);
         }
     }
 }
        public static void ServiceStatusChanged(IntPtr parameter)
        {
            try
            {
                WinApi.Advapi32.SERVICE_NOTIFY n = Marshal.PtrToStructure <WinApi.Advapi32.SERVICE_NOTIFY>(parameter);
                //Log.Main.Trace("Service status: " + n.ServiceStatus.dwCurrentState);
                if (serviceStatus == n.ServiceStatus.dwCurrentState)//on some Windows ServiceStatusChanged is invoked many times!
                {
                    return;
                }
                serviceStatus = n.ServiceStatus.dwCurrentState;
                ServiceControllerStatus status;
                switch (n.ServiceStatus.dwCurrentState)
                {
                case 1:    //stopped
                    status = ServiceControllerStatus.Stopped;
                    _this  = null;
                    break;

                case 4:    //running
                    status = ServiceControllerStatus.Running;
                    lock (instanceContext)
                    {
                        _this?.Unsubscribe();
                        _this?.Close();
                        _this = new CisteraScreenCaptureService.UiApiClient(instanceContext);
                        _this.Subscribe();
                        //beginKeepAliveServiceConnection();//it seems to be redundant because of infinite timeout, but sometimes the channel gets closed due to errors
                    }
                    break;

                default:
                    throw new Exception("Unknown option: " + n.ServiceStatus.dwCurrentState);
                }
                Log.Main.Inform("Service status: " + status);
                SysTray.This.ServiceStateChanged(status);
            }
            catch (Exception e)
            {
                Log.Main.Error(e);
            }
            finally
            {
                serviceStatusChangedManualResetEvent.Set();
            }
        }