From 88bce7dd757299e4881bc4291fbcc623a0650cca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A6=82=E6=84=8F=20=E5=BD=AD?= <2417589739@qq.com> Date: Mon, 12 Sep 2022 16:32:26 +0800 Subject: [PATCH] =?UTF-8?q?=E9=80=9A=E8=AE=AF=E8=BF=9E=E6=8E=A5=E6=B5=8B?= =?UTF-8?q?=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BPASmart.Server/CommunicationServer.cs | 2 +- Communication/RedisHelper.cs | 34 +++++++++++++++++--------- 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/BPASmart.Server/CommunicationServer.cs b/BPASmart.Server/CommunicationServer.cs index 0fb7173e..d4514729 100644 --- a/BPASmart.Server/CommunicationServer.cs +++ b/BPASmart.Server/CommunicationServer.cs @@ -11,7 +11,7 @@ namespace BPASmart.Server public void Init() { BPASmartClient.Message.MessageLog.GetInstance.ShowDebugLog("通讯模块初始化"); - RedisHelper.GetInstance.Connect(); + RedisHelper.GetInstance.ConnectAsync(); Json.Data.CommunicationDevices.ToList()?.ForEach(item => { ThreadManage.GetInstance().Start(new Action(() => diff --git a/Communication/RedisHelper.cs b/Communication/RedisHelper.cs index ccc4abd7..e0e855d6 100644 --- a/Communication/RedisHelper.cs +++ b/Communication/RedisHelper.cs @@ -1,4 +1,5 @@ using ServiceStack.Redis; +using System.Diagnostics; namespace Communication { @@ -10,19 +11,28 @@ namespace Communication private RedisHelper() { } RedisClient client; - public void Connect() + public async Task ConnectAsync() { - if (client == null) - { - client = new RedisClient("124.222.238.75", 16000, "123456", 1); - Thread.Sleep(1000); - //while (!client.HasConnected) - //{ - // client = new RedisClient("124.222.238.75", 16000, "123456"); - // Thread.Sleep(1000); - //} - } - if (client.HasConnected) BPASmartClient.Message.MessageLog.GetInstance.ShowDebugLog("Redis 连接成功"); + return await Task.Factory.StartNew(new Func(() => + { + if (client == null) + { + BPASmartClient.Message.MessageLog.GetInstance.ShowDebugLog("开始连接 Redis"); + client = new RedisClient("124.222.238.75", 16000, "123456", 1); + client.ConnectTimeout = 5000; + Stopwatch sw = new Stopwatch(); + sw.Start(); + while (!client.IsSocketConnected()) + { + if (sw.ElapsedMilliseconds >= client.ConnectTimeout) break; + Thread.Sleep(1000); + } + string status = client.IsSocketConnected() ? "成功" : "失败"; + BPASmartClient.Message.MessageLog.GetInstance.ShowDebugLog($"Redis 连接{status}"); + } + return client.IsSocketConnected(); + })); + } ///