コード例 #1
0
        public void Start(out string errMsg)
        {
            errMsg = "";
            if (IsRuning)
            {
                return;
            }

            // 加载日志数据发布服务所需配置文件信息
            this.mqttParam = new MQTTParam();
            if (!LoadConfig(this.configPath, out errMsg))
            {
                return;
            }

            // 开启MQTT服务当做发布器
            mqttServer = new MQTTServer(mqttParam);
            mqttServer.Start(out errMsg);
            if (!mqttServer.IsRuning || !string.IsNullOrWhiteSpace(errMsg))
            {
                Stop();
                return;
            }

            // 开启消息队列的消费器
            queue = new BlockingCollection <PublishData>();
            task  = new Task(() =>
            {
                foreach (PublishData item in queue.GetConsumingEnumerable())
                {
                    try
                    {
                        ActionTimeout <PublishData> timeout = new ActionTimeout <PublishData>();
                        timeout.Do     = Excute;
                        bool isTimeout = timeout.DoWithTimeout(item, new TimeSpan(0, 0, 0, 5)); //只等待5秒
                        if (isTimeout)                                                          // 超时
                        {
                            GC.Collect();
                        }
                    }
                    catch
                    {
                    }
                }
            }, TaskCreationOptions.LongRunning);
            task.Start();
            IsRuning = true;
        }
コード例 #2
0
        public void Stop()
        {
            if (!IsRuning)
            {
                return;
            }

            // 关闭消息队列的消费器
            // 先完成添加
            queue.CompleteAdding();
            DateTime time1 = DateTime.Now;

            while (queue.Count > 0)
            {
                Thread.Sleep(1);
                // 最多等待10秒避免关不掉
                if (DateTime.Now - time1 > TimeSpan.FromSeconds(10))
                {
                    break;
                }
            }
            while (queue.Count > 0)
            {
                // 等了十秒还没听,队列全部元素废弃
                queue.Take();
            }

            queue = null;
            Task.WaitAll(task);
            task.Dispose();
            task = null;

            // 关闭发布器
            if (mqttServer != null)
            {
                mqttServer.Stop();
            }
            mqttServer = null;

            IsRuning = false;
        }