Procházet zdrojové kódy

replace all DateTime.Now with UTC
add perf moniter

Robert před 1 rokem
rodič
revize
ffcbbc80d0
28 změnil soubory, kde provedl 184 přidání a 116 odebrání
  1. 9 0
      BufferedCurrentTime/BufferedCurrentTime.csproj
  2. 28 0
      BufferedCurrentTime/CurrentTimeGetter.cs
  3. 6 0
      EVCB_OCPP.Server.sln
  4. 1 1
      EVCB_OCPP.WSServer/Jobs/DenyModelCheckJob.cs
  5. 1 1
      EVCB_OCPP.WSServer/Jobs/HealthCheckTriggerJob.cs
  6. 2 2
      EVCB_OCPP.WSServer/Jobs/HeartBeatCheckJob.cs
  7. 2 1
      EVCB_OCPP.WSServer/Jobs/ServerMessageJob.cs
  8. 2 2
      EVCB_OCPP.WSServer/Jobs/ServerSetFeeJob.cs
  9. 2 2
      EVCB_OCPP.WSServer/Jobs/ServerUpdateJob.cs
  10. 2 2
      EVCB_OCPP.WSServer/Jobs/ServerWeatherNotificationJob.cs
  11. 1 1
      EVCB_OCPP.WSServer/Jobs/SmartChargingJob.cs
  12. 38 26
      EVCB_OCPP.WSServer/Message/CoreProfileHandler.cs
  13. 4 4
      EVCB_OCPP.WSServer/Message/FirmwareManagementProfileHandler.cs
  14. 3 3
      EVCB_OCPP.WSServer/Message/LocalAuthListManagementProfileHandler.cs
  15. 2 2
      EVCB_OCPP.WSServer/Message/RemoteTriggerHandler.cs
  16. 4 4
      EVCB_OCPP.WSServer/Message/ReservationProfileHandler.cs
  17. 6 6
      EVCB_OCPP.WSServer/Message/SmartChargingProfileHandler.cs
  18. 3 3
      EVCB_OCPP.WSServer/Program.cs
  19. 15 9
      EVCB_OCPP.WSServer/ProtalServer.cs
  20. 2 2
      EVCB_OCPP.WSServer/Service/BusinessServiceFactory.cs
  21. 13 10
      EVCB_OCPP.WSServer/Service/HttpClientService.cs
  22. 1 1
      SocketBase/AppServer.cs
  23. 4 4
      SocketBase/AppServerBase.cs
  24. 11 9
      SocketBase/AppSession.cs
  25. 1 1
      SocketEngine/ConfigurationWatcher.cs
  26. 3 3
      SuperWebSocket/WebSocketServer.cs
  27. 2 1
      SuperWebSocket/WebSocketSession.cs
  28. 16 16
      TestTool.RemoteTriggerAPP/MainWindow.xaml.cs

+ 9 - 0
BufferedCurrentTime/BufferedCurrentTime.csproj

@@ -0,0 +1,9 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+  <PropertyGroup>
+    <TargetFramework>net7.0</TargetFramework>
+    <ImplicitUsings>enable</ImplicitUsings>
+    <Nullable>enable</Nullable>
+  </PropertyGroup>
+
+</Project>

+ 28 - 0
BufferedCurrentTime/CurrentTimeGetter.cs

@@ -0,0 +1,28 @@
+namespace System;
+
+public class CurrentTimeGetter
+{
+    private static int lastTicks = -1;
+    private static DateTime lastDateTime = DateTime.MinValue;
+
+    /// <summary>        
+    /// Gets the current time in an optimized fashion.        
+    /// </summary>        
+    /// <value>Current time.</value>        
+
+    public static DateTime Now
+    {
+        get
+        {
+            int tickCount = Environment.TickCount;
+            if (tickCount == lastTicks)
+            {
+                return lastDateTime;
+            }
+            DateTime dt = DateTime.Now;
+            lastTicks = tickCount;
+            lastDateTime = dt;
+            return dt;
+        }
+    }
+}

+ 6 - 0
EVCB_OCPP.Server.sln

@@ -15,6 +15,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SuperSocket.SocketEngine",
 EndProject
 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SuperSocket.Common", "SocketCommon\SuperSocket.Common.csproj", "{8241B98B-A7BF-4FBA-BD0B-B1536DDD1A72}"
 EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BufferedCurrentTime", "BufferedCurrentTime\BufferedCurrentTime.csproj", "{32A60C0D-54EF-4850-856B-B8872CD86C6E}"
+EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Any CPU = Debug|Any CPU
@@ -45,6 +47,10 @@ Global
 		{8241B98B-A7BF-4FBA-BD0B-B1536DDD1A72}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{8241B98B-A7BF-4FBA-BD0B-B1536DDD1A72}.Release|Any CPU.ActiveCfg = Release|Any CPU
 		{8241B98B-A7BF-4FBA-BD0B-B1536DDD1A72}.Release|Any CPU.Build.0 = Release|Any CPU
+		{32A60C0D-54EF-4850-856B-B8872CD86C6E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{32A60C0D-54EF-4850-856B-B8872CD86C6E}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{32A60C0D-54EF-4850-856B-B8872CD86C6E}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{32A60C0D-54EF-4850-856B-B8872CD86C6E}.Release|Any CPU.Build.0 = Release|Any CPU
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE

+ 1 - 1
EVCB_OCPP.WSServer/Jobs/DenyModelCheckJob.cs

@@ -33,7 +33,7 @@ public class DenyModelCheckJob : IJob
 
     public async Task Execute(IJobExecutionContext context)
     {
-        logger.LogDebug("{0} Started", nameof(DenyModelCheckJob));
+        //logger.LogDebug("{0} Started", nameof(DenyModelCheckJob));
         try
         {
             using (SqlConnection conn = new SqlConnection(webConnectionString))

+ 1 - 1
EVCB_OCPP.WSServer/Jobs/HealthCheckTriggerJob.cs

@@ -26,7 +26,7 @@ public class HealthCheckTriggerJob : IJob
 
     public async Task Execute(IJobExecutionContext context)
     {
-        logger.LogDebug("{0} Started", nameof(HealthCheckTriggerJob));
+        //logger.LogDebug("{0} Started", nameof(HealthCheckTriggerJob));
 
         Dictionary<string, ClientData> _copyClientDic = protalServer.ClientDic;
 

+ 2 - 2
EVCB_OCPP.WSServer/Jobs/HeartBeatCheckJob.cs

@@ -32,7 +32,7 @@ public class HeartBeatCheckJob : IJob
 
     public async Task Execute(IJobExecutionContext context)
     {
-        logger.LogDebug("{0} Started", nameof(HeartBeatCheckJob));
+        //logger.LogDebug("{0} Started", nameof(HeartBeatCheckJob));
         try
         {
             Stopwatch watch = new Stopwatch();
@@ -45,7 +45,7 @@ public class HeartBeatCheckJob : IJob
 
             foreach (var session in clients)
             {
-                using (var db = await maindbContextFactory.CreateDbContextAsync())
+                using (var db = maindbContextFactory.CreateDbContext())
                 {
                     var machine = new Machine() { Id = session.MachineId };
                     if (machine != null)

+ 2 - 1
EVCB_OCPP.WSServer/Jobs/ServerMessageJob.cs

@@ -11,6 +11,7 @@ using OCPPServer.Protocol;
 using Quartz;
 using System;
 using System.Collections.Generic;
+using System.Diagnostics;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
@@ -52,7 +53,7 @@ public class ServerMessageJob : IJob
         protalServer.RemoveConfirmMessage();
 
         BasicMessageHandler msgAnalyser = new BasicMessageHandler();
-        using (var db = await maindbContextFactory.CreateDbContextAsync())
+        using (var db = maindbContextFactory.CreateDbContext())
         {
             var dateTimeNoew = DateTime.UtcNow;
             DateTime startDt = dateTimeNoew.AddSeconds(-30);

+ 2 - 2
EVCB_OCPP.WSServer/Jobs/ServerSetFeeJob.cs

@@ -42,7 +42,7 @@ public class ServerSetFeeJob : IJob
 
     public async Task Execute(IJobExecutionContext context)
     {
-        logger.LogDebug("{0} Started", nameof(ServerSetFeeJob));
+        //logger.LogDebug("{0} Started", nameof(ServerSetFeeJob));
         BasicMessageHandler msgAnalyser = new BasicMessageHandler();
         Dictionary<string, ClientData> _copyClientDic = protalServer.ClientDic;
         foreach (var item in _copyClientDic)
@@ -64,7 +64,7 @@ public class ServerSetFeeJob : IJob
                 protalServer.UpdateClientDisplayPrice(item.Key, displayPriceText);
 
                 var _CheckFeeDt = DateTime.UtcNow;
-                using (var db = await maindbContextFactory.CreateDbContextAsync())
+                using (var db = maindbContextFactory.CreateDbContext())
                 {
                     db.ServerMessage.Add(new ServerMessage()
                     {

+ 2 - 2
EVCB_OCPP.WSServer/Jobs/ServerUpdateJob.cs

@@ -33,11 +33,11 @@ public class ServerUpdateJob : IJob
 
     public async Task Execute(IJobExecutionContext context)
     {
-        logger.LogDebug("{0} Started", nameof(ServerUpdateJob));
+        //logger.LogDebug("{0} Started", nameof(ServerUpdateJob));
         BasicMessageHandler msgAnalyser = new BasicMessageHandler();
         Dictionary<string, ClientData> _copyClientDic = protalServer.ClientDic;
         var checkUpdateDt = DateTime.UtcNow;
-        using (var db = await maindbContextFactory.CreateDbContextAsync())
+        using (var db = maindbContextFactory.CreateDbContext())
         {
             //var needUpdateChargers = db.Machine.Where(x => x.FW_AssignedMachineVersionId.HasValue == true &&
             //    x.FW_AssignedMachineVersionId != x.FW_VersionReport && x.Online == true)

+ 2 - 2
EVCB_OCPP.WSServer/Jobs/ServerWeatherNotificationJob.cs

@@ -40,7 +40,7 @@ public class ServerWeatherNotificationJob : IJob
 
     public async Task Execute(IJobExecutionContext context)
     {
-        logger.LogDebug("{0} Started", nameof(ServerWeatherNotificationJob));
+        //logger.LogDebug("{0} Started", nameof(ServerWeatherNotificationJob));
         // Console.WriteLine("in...............ServerWeatherNotificationTrigger");
         BasicMessageHandler msgAnalyser = new BasicMessageHandler();
         Dictionary<string, ClientData> _copyClientDic = protalServer.ClientDic;
@@ -164,7 +164,7 @@ public class ServerWeatherNotificationJob : IJob
         var clients = _copyClientDic.Where(x => x.Value.CustomerId == new Guid("009E603C-79CD-4620-A2B8-D9349C0E8AD8")).
         Select(x => new { ChargeBoxId = x.Value.ChargeBoxId, StationLocation = x.Value.StationLocation }).ToList();
 
-        using (var db = await maindbContextFactory.CreateDbContextAsync())
+        using (var db = maindbContextFactory.CreateDbContext())
         {
 
             foreach (var client in clients)

+ 1 - 1
EVCB_OCPP.WSServer/Jobs/SmartChargingJob.cs

@@ -34,7 +34,7 @@ public class SmartChargingJob : IJob
 
     public async Task Execute(IJobExecutionContext context)
     {
-        logger.LogDebug("{0} Started", nameof(SmartChargingJob));
+        //logger.LogDebug("{0} Started", nameof(SmartChargingJob));
         List<StationInfoDto> stations = null;
         using (SqlConnection conn = new SqlConnection(webConnectionString))
         {

+ 38 - 26
EVCB_OCPP.WSServer/Message/CoreProfileHandler.cs

@@ -94,7 +94,8 @@ internal partial class ProfileHandler
     async internal Task<MessageResult> ExecuteCoreRequest(Actions action, ClientData session, IRequest request)
     {
         Stopwatch watch = new Stopwatch();
-        if (action == Actions.Heartbeat)
+        long getDateTimeTime, getServiceTime, getTagInfoTime, dbOpTime = 0;
+        if (action == Actions.Heartbeat || action == Actions.StopTransaction)
         {
             watch.Start();
         }
@@ -173,7 +174,7 @@ internal partial class ProfileHandler
 
                             logger.LogDebug("{0}\r\n{1}\r\n{2}", jo["txId"].Value<int>(), jo["dataString"].Value<string>(), jo["publicKey"].Value<string>());
 
-                            using (var db = await maindbContextFactory.CreateDbContextAsync())
+                            using (var db = maindbContextFactory.CreateDbContext())
                             {
                                 db.OCMF.Add(new OCMF()
                                 {
@@ -197,7 +198,7 @@ internal partial class ProfileHandler
                     {
                         BootNotificationRequest _request = request as BootNotificationRequest;
                         int heartbeat_interval = GlobalConfig.GetHEARTBEAT_INTERVAL();
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var _machine = await db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefaultAsync();
                             _machine.ChargeBoxSerialNumber = string.IsNullOrEmpty(_request.chargeBoxSerialNumber) ? string.Empty : _request.chargeBoxSerialNumber;
@@ -215,7 +216,7 @@ internal partial class ProfileHandler
                         }
 
 
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var configVaule = await db.MachineConfigurations
                                 .Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.HeartbeatInterval)
@@ -240,7 +241,7 @@ internal partial class ProfileHandler
                         StatusNotificationRequest _request = request as StatusNotificationRequest;
                         int preStatus = 0;
                         ConnectorStatus _oldStatus;
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             _oldStatus = await db.ConnectorStatus.Where(x => x.ChargeBoxId == session.ChargeBoxId
                             && x.ConnectorId == _request.connectorId).AsNoTracking().FirstOrDefaultAsync();
@@ -249,7 +250,7 @@ internal partial class ProfileHandler
 
                         if (_oldStatus != null && (_request.status != (ChargePointStatus)_oldStatus.Status || _request.status == ChargePointStatus.Faulted))
                         {
-                            using (var db = await maindbContextFactory.CreateDbContextAsync())
+                            using (var db = maindbContextFactory.CreateDbContext())
                             {
                                 preStatus = _oldStatus.Status;
 
@@ -278,7 +279,7 @@ internal partial class ProfileHandler
 
                         if (_oldStatus == null)
                         {
-                            using (var db = await maindbContextFactory.CreateDbContextAsync())
+                            using (var db = maindbContextFactory.CreateDbContext())
                             {
                                 var _currentStatus = new Domain.Models.Database.ConnectorStatus()
                                 {
@@ -299,7 +300,7 @@ internal partial class ProfileHandler
 
                         if (_request.status == Packet.Messages.SubTypes.ChargePointStatus.Faulted)
                         {
-                            using (var db = await maindbContextFactory.CreateDbContextAsync())
+                            using (var db = maindbContextFactory.CreateDbContext())
                             {
                                 db.MachineError.Add(new MachineError()
                                 {
@@ -370,7 +371,7 @@ internal partial class ProfileHandler
                                             energyRegister = energy_Register.unit.Value == UnitOfMeasure.kWh ? decimal.Multiply(energyRegister, 1000) : energyRegister;
 
 
-                                            using (var maindb = await maindbContextFactory.CreateDbContextAsync())
+                                            using (var maindb = maindbContextFactory.CreateDbContext())
                                             {
                                                 meterStart = await maindb.TransactionRecord
                                                     .Where(x => x.Id == _request.transactionId.Value).Select(x => x.MeterStart)
@@ -427,7 +428,7 @@ internal partial class ProfileHandler
                                 if (session.IsBilling)
                                     if (session.IsBilling)
                                     {
-                                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                                        using (var db = maindbContextFactory.CreateDbContext())
                                         {
                                             db.ServerMessage.Add(new ServerMessage()
                                             {
@@ -525,7 +526,7 @@ internal partial class ProfileHandler
                         }
 
 
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var _CustomerId = await db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).Include(x => x.Customer).
                                  Select(x => x.CustomerId).FirstOrDefaultAsync();
@@ -594,19 +595,23 @@ internal partial class ProfileHandler
 
                         int _ConnectorId = 0;
 
+                        var utcNow = DateTime.UtcNow;
+                        getDateTimeTime = watch.ElapsedMilliseconds;
                         var businessService = await serviceProvider.GetService<BusinessServiceFactory>().CreateBusinessService(session.CustomerId.ToString());
+                        getServiceTime = watch.ElapsedMilliseconds;
 
                         var _idTagInfo = string.IsNullOrEmpty(_request.idTag) ? null : (_request.idTag == "Backend" ?
-                            new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted } : (await businessService.Authorize(session.ChargeBoxId, _request.idTag)).IdTagInfo);
+                            new IdTagInfo() { expiryDate = utcNow.AddDays(1), status = AuthorizationStatus.Accepted } : (await businessService.Authorize(session.ChargeBoxId, _request.idTag)).IdTagInfo);
+                        getTagInfoTime = watch.ElapsedMilliseconds;
 
                         //特例****飛宏客戶旗下的電樁,若遇到Portal沒回應的狀況 ~允許充電
                         if (session.CustomerId.ToString().ToUpper() == "8456AED9-6DD9-4BF3-A94C-9F5DCB9506F7" && _idTagInfo != null && _idTagInfo.status == AuthorizationStatus.ConcurrentTx)
                         {
-                            _idTagInfo = new IdTagInfo() { expiryDate = DateTime.UtcNow.AddDays(1), status = AuthorizationStatus.Accepted };
+                            _idTagInfo = new IdTagInfo() { expiryDate = utcNow.AddDays(1), status = AuthorizationStatus.Accepted };
                         }
                         try
                         {                              
-                            using (var db = await maindbContextFactory.CreateDbContextAsync())
+                            using (var db = maindbContextFactory.CreateDbContext())
                             {
                                 var transaction = await db.TransactionRecord.Where(x => x.Id == _request.transactionId
                                  && x.ChargeBoxId == session.ChargeBoxId).FirstOrDefaultAsync();
@@ -680,7 +685,7 @@ internal partial class ProfileHandler
                                         {
                                             ChargeBoxId = session.ChargeBoxId,
                                             CreatedBy = "Server",
-                                            CreatedOn = DateTime.UtcNow,
+                                            CreatedOn = utcNow,
                                             OutAction = Actions.DataTransfer.ToString(),
                                             OutRequest = JsonConvert.SerializeObject(
                                                        new DataTransferRequest()
@@ -708,7 +713,7 @@ internal partial class ProfileHandler
 
                                 }
                             }
-
+                            dbOpTime = watch.ElapsedMilliseconds;
                             #region Save MeterValue
 
                             if (_request.transactionData != null && 
@@ -757,6 +762,13 @@ internal partial class ProfileHandler
                             result.Success = false;
                             // return result;
                         }
+
+                        watch.Stop();
+                        if (watch.ElapsedMilliseconds > 1000)
+                        {
+                            logger.Log( LogLevel.Critical, "ExecuteCoreRequest {action} {sessisonId} too long {time} sec", action.ToString(), session.SessionID , watch.ElapsedMilliseconds / 1000);
+                            logger.Log(LogLevel.Critical, "{action} {sessisonId} time {getDateTime}/{serviceTime}/{tagInfoTime}/{dbOpTime}", action.ToString(), session.SessionID, getDateTimeTime/1000 , getServiceTime/1000, getTagInfoTime/1000, dbOpTime/1000);
+                        }
                     }
                     break;
                 case Actions.Authorize:
@@ -854,7 +866,7 @@ internal partial class ProfileHandler
                     {
                         DataTransferConfirmation _confirm = confirm as DataTransferConfirmation;
                         DataTransferRequest _request = _confirm.GetRequest() as DataTransferRequest;
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -1307,7 +1319,7 @@ internal partial class ProfileHandler
                         ChangeAvailabilityConfirmation _confirm = confirm as ChangeAvailabilityConfirmation;
                         ChangeAvailabilityRequest _request = _confirm.GetRequest() as ChangeAvailabilityRequest;
 
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -1329,7 +1341,7 @@ internal partial class ProfileHandler
                         ClearCacheConfirmation _confirm = confirm as ClearCacheConfirmation;
                         ClearCacheRequest _request = _confirm.GetRequest() as ClearCacheRequest;
 
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -1350,7 +1362,7 @@ internal partial class ProfileHandler
                         RemoteStartTransactionConfirmation _confirm = confirm as RemoteStartTransactionConfirmation;
                         RemoteStartTransactionRequest _request = _confirm.GetRequest() as RemoteStartTransactionRequest;
 
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -1371,7 +1383,7 @@ internal partial class ProfileHandler
                         RemoteStopTransactionConfirmation _confirm = confirm as RemoteStopTransactionConfirmation;
                         RemoteStopTransactionRequest _request = _confirm.GetRequest() as RemoteStopTransactionRequest;
 
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -1392,7 +1404,7 @@ internal partial class ProfileHandler
                         ResetConfirmation _confirm = confirm as ResetConfirmation;
                         ResetRequest _request = _confirm.GetRequest() as ResetRequest;
 
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -1413,7 +1425,7 @@ internal partial class ProfileHandler
                         ChangeConfigurationConfirmation _confirm = confirm as ChangeConfigurationConfirmation;
                         ChangeConfigurationRequest _request = _confirm.GetRequest() as ChangeConfigurationRequest;
 
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                      x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -1461,7 +1473,7 @@ internal partial class ProfileHandler
                             GetConfigurationConfirmation _confirm = confirm as GetConfigurationConfirmation;
                             //  GetConfigurationRequest _request = _confirm.GetRequest() as GetConfigurationRequest;
 
-                            using (var db = await maindbContextFactory.CreateDbContextAsync())
+                            using (var db = maindbContextFactory.CreateDbContext())
                             {
                                 var configure = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId).ToList();
 
@@ -1558,7 +1570,7 @@ internal partial class ProfileHandler
                         UnlockConnectorConfirmation _confirm = confirm as UnlockConnectorConfirmation;
                         UnlockConnectorRequest _request = _confirm.GetRequest() as UnlockConnectorRequest;
 
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -1613,7 +1625,7 @@ internal partial class ProfileHandler
                         logger.LogDebug(string.Format("DataTransfer Error {0}: {1}", session.ChargeBoxId, requestId));
                     }
 
-                    using (var db = await maindbContextFactory.CreateDbContextAsync())
+                    using (var db = maindbContextFactory.CreateDbContext())
                     {
                         var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                         x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();

+ 4 - 4
EVCB_OCPP.WSServer/Message/FirmwareManagementProfileHandler.cs

@@ -30,7 +30,7 @@ namespace EVCB_OCPP.WSServer.Message
                             if (_request.status == Packet.Messages.SubTypes.FirmwareStatus.Idle)
                             {
                                 string requestId = Guid.NewGuid().ToString();
-                                using (var db = await maindbContextFactory.CreateDbContextAsync())
+                                using (var db = maindbContextFactory.CreateDbContext())
                                 {
                                     var machine = await db.Machine.Where(x => x.FW_AssignedVersion.HasValue == true && x.FW_AssignedVersion.HasValue
                                        && x.FW_AssignedVersion != x.FW_VersionReport && x.ChargeBoxId == session.ChargeBoxId)
@@ -85,7 +85,7 @@ namespace EVCB_OCPP.WSServer.Message
                             }
                             else
                             {
-                                using (var db = await maindbContextFactory.CreateDbContextAsync())
+                                using (var db = maindbContextFactory.CreateDbContext())
                                 {
                                     var item = await db.MachineOperateRecord.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.RequestType == 0)
                                         .OrderByDescending(x => x.CreatedOn).FirstOrDefaultAsync();
@@ -163,7 +163,7 @@ namespace EVCB_OCPP.WSServer.Message
                             var confirmation = confirm as GetDiagnosticsConfirmation;
                             evse_rep = confirmation.fileName;
                         }
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord
                                 .Where(x => x.SerialNo == requestId && x.ChargeBoxId == session.ChargeBoxId && x.Status == 0)
@@ -201,7 +201,7 @@ namespace EVCB_OCPP.WSServer.Message
                 case Actions.GetDiagnostics:
                 case Actions.DiagnosticsStatusNotification:
                     {
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord
                                 .Where(x => x.SerialNo == requestId && x.ChargeBoxId == session.ChargeBoxId && x.Status == 0)

+ 3 - 3
EVCB_OCPP.WSServer/Message/LocalAuthListManagementProfileHandler.cs

@@ -22,7 +22,7 @@ namespace EVCB_OCPP.WSServer.Message
                     {
                         GetLocalListVersionConfirmation _confirm = confirm as GetLocalListVersionConfirmation;
                         GetLocalListVersionRequest _request = _confirm.GetRequest() as GetLocalListVersionRequest;
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -42,7 +42,7 @@ namespace EVCB_OCPP.WSServer.Message
                     {
                         SendLocalListConfirmation _confirm = confirm as SendLocalListConfirmation;
                         SendLocalListRequest _request = _confirm.GetRequest() as SendLocalListRequest;
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -77,7 +77,7 @@ namespace EVCB_OCPP.WSServer.Message
                 case Actions.SendLocalList:
                 case Actions.GetLocalListVersion:
                     {
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();

+ 2 - 2
EVCB_OCPP.WSServer/Message/RemoteTriggerHandler.cs

@@ -24,7 +24,7 @@ namespace EVCB_OCPP.WSServer.Message
                     {
                         TriggerMessageConfirmation _confirm = confirm as TriggerMessageConfirmation;
                         TriggerMessageRequest _request = _confirm.GetRequest() as TriggerMessageRequest;
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -58,7 +58,7 @@ namespace EVCB_OCPP.WSServer.Message
             {
                 case Actions.TriggerMessage:
                     {
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();

+ 4 - 4
EVCB_OCPP.WSServer/Message/ReservationProfileHandler.cs

@@ -24,7 +24,7 @@ namespace EVCB_OCPP.WSServer.Message
                     {
                         ReserveNowConfirmation _confirm = confirm as ReserveNowConfirmation;
                         ReserveNowRequest _request = _confirm.GetRequest() as ReserveNowRequest;
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -44,7 +44,7 @@ namespace EVCB_OCPP.WSServer.Message
                     {
                         CancelReservationConfirmation _confirm = confirm as CancelReservationConfirmation;
                         CancelReservationRequest _request = _confirm.GetRequest() as CancelReservationRequest;
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -78,7 +78,7 @@ namespace EVCB_OCPP.WSServer.Message
             {
                 case Actions.ReserveNow:
                     {
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -96,7 +96,7 @@ namespace EVCB_OCPP.WSServer.Message
                     break;
                 case Actions.CancelReservation:
                     {
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();

+ 6 - 6
EVCB_OCPP.WSServer/Message/SmartChargingProfileHandler.cs

@@ -20,7 +20,7 @@ namespace EVCB_OCPP.WSServer.Message
 
         internal async void SetChargingProfile(string chargeBoxId, decimal value, ChargingRateUnitType unit)
         {
-            using (var db = await maindbContextFactory.CreateDbContextAsync())
+            using (var db = maindbContextFactory.CreateDbContext())
             {
                 var _setProfileRequest = new SetChargingProfileRequest()
                 {
@@ -64,7 +64,7 @@ namespace EVCB_OCPP.WSServer.Message
 
         internal async void ClearChargingProfile(string chargeBoxId)
         {
-            using (var db = await maindbContextFactory.CreateDbContextAsync())
+            using (var db = maindbContextFactory.CreateDbContext())
             {
                 var _clearProfileRequest = new ClearChargingProfileRequest()
                 {
@@ -100,7 +100,7 @@ namespace EVCB_OCPP.WSServer.Message
                     {
                         ClearChargingProfileConfirmation _confirm = confirm as ClearChargingProfileConfirmation;
                         ClearChargingProfileRequest _request = _confirm.GetRequest() as ClearChargingProfileRequest;
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -120,7 +120,7 @@ namespace EVCB_OCPP.WSServer.Message
                     {
                         SetChargingProfileConfirmation _confirm = confirm as SetChargingProfileConfirmation;
                         SetChargingProfileRequest _request = _confirm.GetRequest() as SetChargingProfileRequest;
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord.Where(x => x.SerialNo == requestId &&
                             x.ChargeBoxId == session.ChargeBoxId && x.Status == 0).FirstOrDefaultAsync();
@@ -140,7 +140,7 @@ namespace EVCB_OCPP.WSServer.Message
                     {
                         GetCompositeScheduleConfirmation _confirm = confirm as GetCompositeScheduleConfirmation;
                         GetCompositeScheduleRequest _request = _confirm.GetRequest() as GetCompositeScheduleRequest;
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord
                                 .Where(x => x.SerialNo == requestId && x.ChargeBoxId == session.ChargeBoxId && x.Status == 0)
@@ -177,7 +177,7 @@ namespace EVCB_OCPP.WSServer.Message
                 case Actions.SetChargingProfile:
                 case Actions.GetCompositeSchedule:
                     {
-                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                        using (var db = maindbContextFactory.CreateDbContext())
                         {
                             var operation = await db.MachineOperateRecord
                                 .Where(x => x.SerialNo == requestId && x.ChargeBoxId == session.ChargeBoxId && x.Status == 0)

+ 3 - 3
EVCB_OCPP.WSServer/Program.cs

@@ -45,19 +45,19 @@ namespace EVCB_OCPP.WSServer
                 .UseNLog()
                 .ConfigureServices((hostContext, services) =>
                 {
-                    services.AddDbContextFactory<MainDBContext>((options) => {
+                    services.AddPooledDbContextFactory<MainDBContext>((options) => {
                         var cString = hostContext.Configuration.GetConnectionString("MainDBContext");
                         options.UseSqlServer(cString, dbOptions => {
                             dbOptions.CommandTimeout(180);
                         });
                     });
-                    services.AddDbContextFactory<MeterValueDBContext>((options) => {
+                    services.AddPooledDbContextFactory<MeterValueDBContext>((options) => {
                         var cString = hostContext.Configuration.GetConnectionString("MeterValueDBContext");
                         options.UseSqlServer(cString, dbOptions => {
                             dbOptions.CommandTimeout(180);
                         });
                     });
-                    services.AddDbContextFactory<ConnectionLogDBContext>((options) => {
+                    services.AddPooledDbContextFactory<ConnectionLogDBContext>((options) => {
                         var cString = hostContext.Configuration.GetConnectionString("ConnectionLogDBContext");
                         options.UseSqlServer(cString, dbOptions => {
                             dbOptions.CommandTimeout(180);

+ 15 - 9
EVCB_OCPP.WSServer/ProtalServer.cs

@@ -451,7 +451,7 @@ namespace EVCB_OCPP.WSServer
         private async void CheckEVSEConfigure(string chargeBoxId)
         {
             if (string.IsNullOrEmpty(chargeBoxId)) return;
-            using (var db = await maindbContextFactory.CreateDbContextAsync())
+            using (var db = maindbContextFactory.CreateDbContext())
             {
                 db.ServerMessage.Add(new ServerMessage()
                 {
@@ -532,7 +532,7 @@ namespace EVCB_OCPP.WSServer
 
         private void AppServer_SessionClosed(ClientData session, CloseReason value)
         {
-            WriteMachineLog(session, string.Format("CloseReason: {0}", value), "Connection", "");
+            _ = WriteMachineLog(session, string.Format("CloseReason: {0}", value), "Connection", "");
             RemoveClient(session);
         }
 
@@ -822,6 +822,7 @@ namespace EVCB_OCPP.WSServer
 
         async private void ProcessRequestMessage(MessageResult analysisResult, ClientData session, Actions action)
         {
+            Stopwatch outter_stopwatch = Stopwatch.StartNew();
             BasicMessageHandler msgAnalyser = new BasicMessageHandler();
             if (!session.IsCheckIn && action != Actions.BootNotification)
             {
@@ -835,8 +836,8 @@ namespace EVCB_OCPP.WSServer
                 {
                     case "Core":
                         {
-
                             var replyResult = await profileHandler.ExecuteCoreRequest(action, session, (IRequest)analysisResult.Message).ConfigureAwait(false);
+
                             if (replyResult.Success)
                             {
                                 string response = BasicMessageHandler.GenerateConfirmation(analysisResult.UUID, (IConfirmation)replyResult.Message);
@@ -852,7 +853,7 @@ namespace EVCB_OCPP.WSServer
                                         CheckEVSEConfigure(session.ChargeBoxId);
                                         if (session.CustomerId == new Guid("298918C0-6BB5-421A-88CC-4922F918E85E") || session.CustomerId == new Guid("9E6BFDCC-09FB-4DAB-A428-43FE507600A3"))
                                         {
-                                            using (var db = await maindbContextFactory.CreateDbContextAsync())
+                                            using (var db = maindbContextFactory.CreateDbContext())
                                             {
                                                 db.ServerMessage.Add(new ServerMessage()
                                                 {
@@ -881,7 +882,7 @@ namespace EVCB_OCPP.WSServer
                                     }
                                     else
                                     {
-                                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                                        using (var db = maindbContextFactory.CreateDbContext())
                                         {
                                             var machine = await db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId).FirstOrDefaultAsync();
                                             if (machine != null)
@@ -904,7 +905,7 @@ namespace EVCB_OCPP.WSServer
                                     var authorizeRequest = (IRequest)analysisResult.Message as AuthorizeRequest;
                                     if (session.UserDisplayPrices.ContainsKey(authorizeRequest.idTag))
                                     {
-                                        using (var db = await maindbContextFactory.CreateDbContextAsync())
+                                        using (var db = maindbContextFactory.CreateDbContext())
                                         {
                                             db.ServerMessage.Add(new ServerMessage()
                                             {
@@ -1048,6 +1049,11 @@ namespace EVCB_OCPP.WSServer
 
                 }
             }
+            outter_stopwatch.Stop();
+            if (outter_stopwatch.ElapsedMilliseconds > 1000)
+            {
+                logger.Fatal("ProcessRequestMessage {action} too long {time} sec", action.ToString(), outter_stopwatch.ElapsedMilliseconds / 1000);
+            }
         }
 
         async private void ProcessConfirmationMessage(MessageResult analysisResult, ClientData session, Actions action)
@@ -1185,7 +1191,7 @@ namespace EVCB_OCPP.WSServer
 
                 if (session != null)
                 {
-                    WriteMachineLog(session, msg, messageType, errorMsg, true);
+                    WriteMachineLog(session, msg, messageType, errorMsg, true).Wait();
                     session.Send(msg);
                 }
 
@@ -1314,7 +1320,7 @@ namespace EVCB_OCPP.WSServer
                     foundRequest.SentInterval = 0;
                     analysisResult.RequestId = foundRequest.RequestId;
 
-                    using (var db = await maindbContextFactory.CreateDbContextAsync())
+                    using (var db = maindbContextFactory.CreateDbContext())
                     {
                         var sc = await db.ServerMessage.Where(x => x.Id == foundRequest.Id).FirstOrDefaultAsync();
                         sc.InMessage = JsonConvert.SerializeObject(analysisResult.Message, Formatting.None);
@@ -1414,7 +1420,7 @@ namespace EVCB_OCPP.WSServer
 
         }
 
-        private async void WriteMachineLog(ClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
+        private async Task WriteMachineLog(ClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
         {
             try
             {

+ 2 - 2
EVCB_OCPP.WSServer/Service/BusinessServiceFactory.cs

@@ -34,9 +34,9 @@ namespace EVCB_OCPP.WSServer.Service
         public async Task<IBusinessService> CreateBusinessService(string customerId)
         {
             bool isCallOut = false;
-            using (var db = await mainDBContextFactory.CreateDbContextAsync())
+            using (var db = this.mainDBContextFactory.CreateDbContext())
             {
-                isCallOut = db.Customer.Where(x => x.Id == new Guid(customerId)).Select(x => x.CallPartnerApiOnSchedule).SingleOrDefault();
+                isCallOut = await db.Customer.Where(x => x.Id == new Guid(customerId)).Select(x => x.CallPartnerApiOnSchedule).SingleOrDefaultAsync();
             }
 
             //return isCallOut ? new OuterBusinessService(customerId) : new LocalBusinessService(customerId);

+ 13 - 10
EVCB_OCPP.WSServer/Service/HttpClientService.cs

@@ -35,8 +35,8 @@ namespace EVCB_OCPP.WSServer.Service
         public int HandlerLifetime { get => _handlerLifetime; set => _handlerLifetime = value; }
 
 
-        private IHttpClientFactory _clientFactory = null;
-        private IServiceCollection _services = new ServiceCollection();
+        private static IHttpClientFactory _clientFactory = null;
+        //private IServiceCollection _services = new ServiceCollection();
         private int _handlerLifetime = 2;
         private int _maxConnectionsPerServer = 300;
         private int _timeout = 60;
@@ -44,7 +44,18 @@ namespace EVCB_OCPP.WSServer.Service
 
         public HttpClientService(string baseAddress = "")
         {
+            Init(baseAddress);
+        }
+
+
+        private void Init(string baseAddress)
+        {
+            if (_clientFactory is not null)
+            {
+                return;
+            }
 
+            IServiceCollection _services = new ServiceCollection();
             _services.AddHttpClient("Default", c =>
             {
                 if (!string.IsNullOrEmpty(baseAddress))
@@ -64,16 +75,8 @@ namespace EVCB_OCPP.WSServer.Service
                 };
             }));
 
-            Init();
-        }
-
-
-        private void Init()
-        {
             _clientFactory = _services.BuildServiceProvider()
                      .GetRequiredService<IHttpClientFactory>();
-
-
         }
 
 

+ 1 - 1
SocketBase/AppServer.cs

@@ -229,7 +229,7 @@ namespace SuperSocket.SocketBase
                     if (sessionSource == null)
                         return;
 
-                    DateTime now = DateTime.Now;
+                    DateTime now = DateTime.UtcNow;
                     DateTime timeOut = now.AddSeconds(0 - Config.IdleSessionTimeOut);
 
                     var timeOutSessions = sessionSource.Where(s => s.Value.LastActiveTime <= timeOut).Select(s => s.Value);

+ 4 - 4
SocketBase/AppServerBase.cs

@@ -1068,7 +1068,7 @@ namespace SuperSocket.SocketBase
                 return false;
             }
 
-            StartedTime = DateTime.Now;
+            StartedTime = DateTime.UtcNow;
             m_StateCode = ServerStateConst.Running;
 
             m_ServerStatus[StatusInfoKeys.IsRunning] = true;
@@ -1288,7 +1288,7 @@ namespace SuperSocket.SocketBase
                     session.InternalHandleUnknownRequest(requestInfo);
                 }
 
-                session.LastActiveTime = DateTime.Now;
+                session.LastActiveTime = DateTime.UtcNow;
             }
             else
             {
@@ -1304,7 +1304,7 @@ namespace SuperSocket.SocketBase
                 }
                 
                 session.PrevCommand = requestInfo.Key;
-                session.LastActiveTime = DateTime.Now;
+                session.LastActiveTime = DateTime.UtcNow;
 
                 if (Config.LogCommand)
                     Logger.LogInformation("Command - {0}", requestInfo.Key);
@@ -1661,7 +1661,7 @@ namespace SuperSocket.SocketBase
         /// <param name="serverStatus">The server status.</param>
         protected virtual void UpdateServerStatus(StatusInfoCollection serverStatus)
         {
-            DateTime now = DateTime.Now;
+            DateTime now = DateTime.UtcNow;
 
             serverStatus[StatusInfoKeys.IsRunning] = m_StateCode == ServerStateConst.Running;
             serverStatus[StatusInfoKeys.TotalConnections] = this.SessionCount;

+ 11 - 9
SocketBase/AppSession.cs

@@ -171,7 +171,7 @@ namespace SuperSocket.SocketBase
         /// </summary>
         public AppSession()
         {
-            this.StartTime = DateTime.Now;
+            this.StartTime = DateTime.UtcNow;
             this.LastActiveTime = this.StartTime;
         }
 
@@ -331,7 +331,7 @@ namespace SuperSocket.SocketBase
             if (!SocketSession.TrySend(segment))
                 return false;
 
-            LastActiveTime = DateTime.Now;
+            LastActiveTime = DateTime.UtcNow;
             return true;
         }
 
@@ -351,6 +351,8 @@ namespace SuperSocket.SocketBase
 
         private void InternalSend(ArraySegment<byte> segment)
         {
+            var dateTimeNow = DateTime.UtcNow;
+
             if (!m_Connected)
                 return;
 
@@ -365,19 +367,19 @@ namespace SuperSocket.SocketBase
                 throw new TimeoutException("The sending attempt timed out");
             }
 
-            var timeOutTime = sendTimeOut > 0 ? DateTime.Now.AddMilliseconds(sendTimeOut) : DateTime.Now;
+            var timeOutTime = sendTimeOut > 0 ? dateTimeNow.AddMilliseconds(sendTimeOut) : dateTimeNow;
 
-            var spinWait = new SpinWait();
+            //var spinWait = new SpinWait();
 
             while (m_Connected)
             {
-                spinWait.SpinOnce();
+                //spinWait.SpinOnce();
 
                 if (InternalTrySend(segment))
                     return;
 
                 //If sendTimeOut = 0, don't have timeout check
-                if (sendTimeOut > 0 && DateTime.Now >= timeOutTime)
+                if (sendTimeOut > 0 && dateTimeNow >= timeOutTime)
                 {
                     throw new TimeoutException("The sending attempt timed out");
                 }
@@ -398,7 +400,7 @@ namespace SuperSocket.SocketBase
             if (!SocketSession.TrySend(segments))
                 return false;
 
-            LastActiveTime = DateTime.Now;
+            LastActiveTime = DateTime.UtcNow;
             return true;
         }
 
@@ -431,7 +433,7 @@ namespace SuperSocket.SocketBase
                 throw new TimeoutException("The sending attempt timed out");
             }
 
-            var timeOutTime = sendTimeOut > 0 ? DateTime.Now.AddMilliseconds(sendTimeOut) : DateTime.Now;
+            var timeOutTime = sendTimeOut > 0 ? DateTime.UtcNow.AddMilliseconds(sendTimeOut) : DateTime.UtcNow;
 
             var spinWait = new SpinWait();
 
@@ -443,7 +445,7 @@ namespace SuperSocket.SocketBase
                     return;
 
                 //If sendTimeOut = 0, don't have timeout check
-                if (sendTimeOut > 0 && DateTime.Now >= timeOutTime)
+                if (sendTimeOut > 0 && DateTime.UtcNow >= timeOutTime)
                 {
                     throw new TimeoutException("The sending attempt timed out");
                 }

+ 1 - 1
SocketEngine/ConfigurationWatcher.cs

@@ -57,7 +57,7 @@ namespace SuperSocket.SocketEngine
                             return;
 
                         OnConfigFileUpdated(filePath, sectionName, bootstrap);
-                        m_LastUpdatedTime = DateTime.Now;
+                        m_LastUpdatedTime = DateTime.UtcNow;
                     }
                 };
 

+ 3 - 3
SuperWebSocket/WebSocketServer.cs

@@ -423,7 +423,7 @@ namespace SuperWebSocket
                         continue;
                     }
 
-                    if (DateTime.Now < session.StartTime.AddSeconds(m_OpenHandshakeTimeOut))
+                    if (DateTime.UtcNow < session.StartTime.AddSeconds(m_OpenHandshakeTimeOut))
                         break;
 
                     //Timeout, dequeue and then close
@@ -445,7 +445,7 @@ namespace SuperWebSocket
                         continue;
                     }
 
-                    if (DateTime.Now < session.StartClosingHandshakeTime.AddSeconds(m_CloseHandshakeTimeOut))
+                    if (DateTime.UtcNow < session.StartClosingHandshakeTime.AddSeconds(m_CloseHandshakeTimeOut))
                         break;
 
                     //Timeout, dequeue and then close
@@ -718,7 +718,7 @@ namespace SuperWebSocket
                 session.HandleUnknownCommand(requestInfo);
             }
 
-            session.LastActiveTime = DateTime.Now;
+            session.LastActiveTime = DateTime.UtcNow;
         }
 
 

+ 2 - 1
SuperWebSocket/WebSocketSession.cs

@@ -6,6 +6,7 @@ using System.Net;
 using System.Security.Authentication;
 using System.Text;
 using System.Threading;
+using System.Threading.Tasks;
 using Microsoft.Extensions.Logging;
 using SuperSocket.Common;
 using SuperSocket.SocketBase;
@@ -511,7 +512,7 @@ namespace SuperWebSocket
 
             ProtocolProcessor.SendCloseHandshake(this, statusCode, reasonText);
 
-            StartClosingHandshakeTime = DateTime.Now;
+            StartClosingHandshakeTime = DateTime.UtcNow;
             AppServer.PushToCloseHandshakeQueue(this);
         }
 

+ 16 - 16
TestTool.RemoteTriggerAPP/MainWindow.xaml.cs

@@ -421,13 +421,13 @@ namespace TestTool.RemoteTriggerAPP
         private void SetWrongAction()
         {
             bool isError = false;
-            DateTime expiryTime = DateTime.Now;
+            DateTime expiryTime = DateTime.UtcNow;
             try
             {
                 try
                 {
                     expiryTime = Convert.ToDateTime(uxExpiryTimeTb.Text);
-                    //if (expiryTime < DateTime.Now.AddSeconds(60))
+                    //if (expiryTime < DateTime.UtcNow.AddSeconds(60))
                     //{
                     //    isError = true;
                     //    uxMsgTb.Text = string.Format("ExpiryTime is too close or too early to the current time (60 seconds).");
@@ -439,7 +439,7 @@ namespace TestTool.RemoteTriggerAPP
                     if (ex is FormatException)
                     {
                         isError = true;
-                        uxMsgTb.Text = string.Format("ExpiryTime's Format is wrong Example:{0}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
+                        uxMsgTb.Text = string.Format("ExpiryTime's Format is wrong Example:{0}", DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"));
                     }
                 }
                 if (!isError)
@@ -469,13 +469,13 @@ namespace TestTool.RemoteTriggerAPP
         private void ReserveNow()
         {
             bool isError = false;
-            DateTime expiryTime = DateTime.Now;
+            DateTime expiryTime = DateTime.UtcNow;
             try
             {
                 try
                 {
                     expiryTime = Convert.ToDateTime(uxExpiryTimeTb.Text);
-                    //if (expiryTime < DateTime.Now.AddSeconds(60))
+                    //if (expiryTime < DateTime.UtcNow.AddSeconds(60))
                     //{
                     //    isError = true;
                     //    uxMsgTb.Text = string.Format("ExpiryTime is too close or too early to the current time (60 seconds).");
@@ -487,7 +487,7 @@ namespace TestTool.RemoteTriggerAPP
                     if (ex is FormatException)
                     {
                         isError = true;
-                        uxMsgTb.Text = string.Format("ExpiryTime's Format is wrong Example:{0}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
+                        uxMsgTb.Text = string.Format("ExpiryTime's Format is wrong Example:{0}", DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss"));
                     }
                 }
                 if (!isError)
@@ -526,8 +526,8 @@ namespace TestTool.RemoteTriggerAPP
                     location = new Uri(ftp ? Properties.Settings.Default.FTPGetDiagnosticsPreUrl : Properties.Settings.Default.GetDiagnosticsPreUrl),
                     retries = 1,
                     retryInterval = 30,
-                    startTime = DateTime.Now.AddHours(-1).ToUniversalTime(),
-                    stopTime = DateTime.Now.ToUniversalTime()
+                    startTime = DateTime.UtcNow.AddHours(-1).ToUniversalTime(),
+                    stopTime = DateTime.UtcNow.ToUniversalTime()
 
 
                 };
@@ -579,11 +579,11 @@ namespace TestTool.RemoteTriggerAPP
                     //     new AuthorizationData()
                     //     {
 
-                    //          idTagInfo=new IdTagInfo(){  expiryDate=DateTime.Now.ToUniversalTime().AddDays(3), status=  AuthorizationStatus.Accepted},
+                    //          idTagInfo=new IdTagInfo(){  expiryDate=DateTime.UtcNow.ToUniversalTime().AddDays(3), status=  AuthorizationStatus.Accepted},
                     //           idTag="F5902677"
                     //     }, new AuthorizationData()
                     //     {
-                    //          idTagInfo=new IdTagInfo(){  expiryDate=DateTime.Now.ToUniversalTime().AddDays(3), status=  AuthorizationStatus.Expired},
+                    //          idTagInfo=new IdTagInfo(){  expiryDate=DateTime.UtcNow.ToUniversalTime().AddDays(3), status=  AuthorizationStatus.Expired},
                     //           idTag="772690F5"
                     //     }
                     //}
@@ -606,7 +606,7 @@ namespace TestTool.RemoteTriggerAPP
                 {
                     request.localAuthorizationList.Add(new AuthorizationData()
                     {
-                        idTag = DateTime.Now.ToString("yyyyMMddHHmmss" + i.ToString("00000")),
+                        idTag = DateTime.UtcNow.ToString("yyyyMMddHHmmss" + i.ToString("00000")),
                         idTagInfo = new IdTagInfo()
                         {
                             parentIdTag = "0000000000000000001",
@@ -895,7 +895,7 @@ namespace TestTool.RemoteTriggerAPP
             {
                 db.MachineOperateRecord.Add(new MachineOperateRecord()
                 {
-                    CreatedOn = DateTime.Now.ToUniversalTime(),
+                    CreatedOn = DateTime.UtcNow.ToUniversalTime(),
                     ChargeBoxId = uxChargeBoxIdTb.Text,
                     SerialNo = uuid,
                     RequestContent = !string.IsNullOrEmpty(destroyData) ? destroyData : JsonConvert.SerializeObject(request, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
@@ -910,7 +910,7 @@ namespace TestTool.RemoteTriggerAPP
                 {
                     ChargeBoxId = uxChargeBoxIdTb.Text,
                     CreatedBy = !string.IsNullOrEmpty(destroyData) ? "Destroyer" : "TestTool",
-                    CreatedOn = DateTime.Now.ToUniversalTime(),
+                    CreatedOn = DateTime.UtcNow.ToUniversalTime(),
                     OutAction = !string.IsNullOrEmpty(destroyData) ? action : request.Action.ToString(),
                     OutRequest = !string.IsNullOrEmpty(destroyData) ? destroyData : JsonConvert.SerializeObject(request, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None }),
                     SerialNo = uuid,
@@ -962,7 +962,7 @@ namespace TestTool.RemoteTriggerAPP
             }
 
             UploadFile ufObj = new UploadFile();
-            ufObj.CreatedOn = DateTime.Now.ToUniversalTime();
+            ufObj.CreatedOn = DateTime.UtcNow.ToUniversalTime();
             ufObj.FileExtensionName = System.IO.Path.GetExtension(uxUploadFileTb.Text);
             ufObj.Id = Guid.NewGuid().ToString();
             ufObj.FileName = md5 + ufObj.FileExtensionName;
@@ -1059,7 +1059,7 @@ namespace TestTool.RemoteTriggerAPP
             }
 
             UploadFile ufObj = new UploadFile();
-            ufObj.CreatedOn = DateTime.Now.ToUniversalTime();
+            ufObj.CreatedOn = DateTime.UtcNow.ToUniversalTime();
             ufObj.FileExtensionName = System.IO.Path.GetExtension(uxUploadFileTb.Text);
             ufObj.Id = Guid.NewGuid().ToString();
             ufObj.FileName = md5 + ufObj.FileExtensionName;
@@ -1133,7 +1133,7 @@ namespace TestTool.RemoteTriggerAPP
                 {
                     ChargeBoxId = uxChargeBoxIdTb.Text,
                     UploadFileId = publishes[selectedPublish].Id,
-                    CreatedOn = DateTime.Now.ToUniversalTime()
+                    CreatedOn = DateTime.UtcNow.ToUniversalTime()
                 };
 
                 db.MachineVersionFile.Add(obj);