コード例 #1
0
        /// <summary>
        /// 适用于控制台的后台服务框架
        /// </summary>
        /// <param name="configKeyAndFieldNames">需要初始化的配置项字段 key:配置项的key,例:"KeyOfUser",value:配置项的名称,例:nameof(_keyOfUser)</param>
        /// <param name="tryBlock">核心代码</param>
        /// <param name="finallyBlock">清理代码</param>
        /// <param name="userRights">需要的权限</param>
        /// <param name="updateInterval">升级检查时间,默认1小时</param>
        public static void RunAsBackgroundService(Dictionary <string, string> configKeyAndFieldNames, Action tryBlock, Action finallyBlock = null, UserRights userRights = UserRights.NORMAL_USER, int updateInterval = 3600000)
        {
            var mutex           = new Mutex(true, ProductDescription.AppName);
            var exitForUpdating = false;

            try
            {
                EnsureSingleRunning(mutex);

                InitDeployQueryString();

                EnsureUserRights(userRights);

                Info(ApplicationDeployment.IsNetworkDeployed ? $"{ProductDescription.Product} {ProductDescription.Version}" : ProductDescription.AppName);

                InitConfigurations(configKeyAndFieldNames);

                tryBlock?.Invoke();

                var updateWorker = new UpdateCheckingWorker(updateInterval);
                updateWorker.Start();
                updateWorker.WaitForExit();
                exitForUpdating = true;
                Info("找到更新,准备重启...\n");
            }
            catch (Exception ex)
            {
                Error(ex);
                Thread.Sleep(5000);
            }
            finally
            {
                finallyBlock?.Invoke();

                WorkerFactory.StopAll();

                mutex.Close();

                if (exitForUpdating)
                {
                    Application.Restart();
                }
            }
        }