/// <summary> /// 使用用户自定义的解密方法从文件读取数据 /// </summary> /// <param name="decrypt">用户自定义的解密方法</param> public void LoadByFile(Converter <string, string> decrypt) { if (FileSavePath != "") { if (File.Exists(FileSavePath)) { HybirdLock.Enter(); try { using (StreamReader sr = new StreamReader(FileSavePath, Encoding.Default)) { LoadByString(decrypt(sr.ReadToEnd())); } } catch (Exception ex) { ILogNet?.WriteException(StringResources.FileLoadFailed, ex); } finally { HybirdLock.Leave(); } } } }
private int onlineCount = 0; // 在线的客户端的数量 /// <summary> /// 新增一个在线的客户端信息 /// </summary> /// <param name="session">会话内容</param> protected void AddClient(AppSession session) { lockOnlineClient.Enter( ); listsOnlineClient.Add(session); onlineCount++; lockOnlineClient.Leave( ); }
private void ThreadPoolSaveFile(object obj) { // 获取需要存储的日志 HslMessageItem current = GetAndRemoveLogItem(); // 进入文件操作的锁 m_fileSaveLock.Enter(); // 获取要存储的文件名称 string LogSaveFileName = GetFileSaveName(); if (!string.IsNullOrEmpty(LogSaveFileName)) { // 保存 StreamWriter sw = null; try { sw = new StreamWriter(LogSaveFileName, true, Encoding.UTF8); while (current != null) { // 触发事件 OnBeforeSaveToFile(new HslEventArgs( ) { HslMessage = current }); sw.Write(HslMessageFormate(current)); sw.Write(Environment.NewLine); current = GetAndRemoveLogItem(); } } catch (Exception ex) { AddItemToCache(current); AddItemToCache(new HslMessageItem() { Degree = HslMessageDegree.FATAL, Text = LogNetManagment.GetSaveStringFromException("LogNetSelf", ex), }); } finally { sw?.Dispose(); } } // 释放锁 m_fileSaveLock.Leave(); Interlocked.Exchange(ref m_SaveStatus, 0); // 再次检测锁是否释放完成 if (m_WaitForSave.Count > 0) { StartSaveFile(); } }
private SimpleHybirdLock lock_list; // 列表锁 private void AddClient(DeviceState device) { lock_list.Enter( ); list.Add(device); lock_list.Leave( ); ClientOnline?.Invoke(device); }
/// <summary> /// 读取地址的线圈的通断情况 /// </summary> /// <param name="address">起始地址</param> /// <returns><c>True</c>或是<c>False</c></returns> /// <exception cref="IndexOutOfRangeException"></exception> public bool ReadCoil(ushort address) { bool result = false; hybirdLockCoil.Enter( ); result = Coils[address]; hybirdLockCoil.Leave( ); return(result); }
/// <summary> /// 过滤指定的关键字存储 /// </summary> /// <param name="keyWord">关键字</param> public void FiltrateKeyword(string keyWord) { filtrateLock.Enter( ); if (!filtrateKeyword.Contains(keyWord)) { filtrateKeyword.Add(keyWord); } filtrateLock.Leave( ); }
public void SimpleHybirdLockExample( ) { // 同步锁,简单的使用 simpleHybird.Enter( ); // do something simpleHybird.Leave( ); }
private void AddItemToCache(HslMessageItem item) { m_simpleHybirdLock.Enter(); m_WaitForSave.Enqueue(item); m_simpleHybirdLock.Leave(); StartSaveFile(); }
/// <summary> /// 读写ModBus服务器的基础方法,支持任意的数据操作 /// </summary> /// <param name="send">发送的字节数据</param> /// <returns></returns> public OperateResult <byte[]> ReadFromModBusServer(byte[] send) { OperateResult <byte[]> result = new OperateResult <byte[]>(); readModbusLock.Enter(); if (!CreateSocketAndConnect(out System.Net.Sockets.Socket socket, iPEndPoint, result)) { readModbusLock.Leave(); socket = null; return(result); } if (!SendBytesToSocket(socket, send, result, "发送数据到服务器失败")) { readModbusLock.Leave(); return(result); } HslTimeOut hslTimeOut = new HslTimeOut(); hslTimeOut.WorkSocket = socket; hslTimeOut.DelayTime = 5000; // 2秒内接收到数据 try { System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback( ThreadPoolCheckConnect), hslTimeOut); byte[] head = NetSupport.ReadBytesFromSocket(socket, 6); int length = head[4] * 256 + head[5]; byte[] data = NetSupport.ReadBytesFromSocket(socket, length); byte[] buffer = new byte[6 + length]; head.CopyTo(buffer, 0); data.CopyTo(buffer, 6); hslTimeOut.IsSuccessful = true; result.Content = buffer; } catch (Exception ex) { socket?.Close(); result.Message = "从服务器接收结果数据的时候发生错误:" + ex.Message; readModbusLock.Leave(); return(result); } socket?.Close(); readModbusLock.Leave(); result.IsSuccess = true; return(result); }
/// <summary> /// 读取自定义的寄存器的值 /// </summary> /// <param name="address">起始地址</param> /// <param name="length">数据长度</param> /// <exception cref="IndexOutOfRangeException"></exception> /// <returns>byte数组值</returns> public byte[] ReadRegister(ushort address, ushort length) { byte[] buffer = new byte[length * 2]; hybirdLockRegister.Enter( ); for (int i = 0; i < buffer.Length; i++) { buffer[i] = Register[address * 2 + i]; } hybirdLockRegister.Leave( ); return(buffer); }
/// <summary> /// 读取一个寄存器的值 /// </summary> /// <param name="address">起始地址</param> /// <exception cref="IndexOutOfRangeException"></exception> /// <returns></returns> public short ReadShortRegister(ushort address) { byte[] buffer = new byte[2]; hybirdLockRegister.Enter(); buffer[0] = Register[address + 1]; buffer[1] = Register[address]; hybirdLockRegister.Leave(); return(BitConverter.ToInt16(buffer, 0)); }
/// <summary> /// 使用底层的数据报文来通讯,传入需要发送的消息,返回一条完整的数据指令 /// </summary> /// <param name="send">发送的完整的报文信息</param> /// <returns>接收的完整的报文信息</returns> public OperateResult <byte[]> ReadFromCoreServer(byte[] send) { var result = new OperateResult <byte[]>( ); // string tmp1 = BasicFramework.SoftBasic.ByteToHexString( send, '-' ); InteractiveLock.Enter( ); // 获取有用的网络通道,如果没有,就建立新的连接 OperateResult <Socket> resultSocket = GetAvailableSocket( ); if (!resultSocket.IsSuccess) { IsSocketError = true; InteractiveLock.Leave( ); result.CopyErrorFromOther(resultSocket); return(result); } var read = ReadFromCoreServerBase(resultSocket.Content, send); if (read.IsSuccess) { IsSocketError = false; result.IsSuccess = read.IsSuccess; result.Content = new byte[read.Content1.Length + read.Content2.Length]; if (read.Content1.Length > 0) { read.Content1.CopyTo(result.Content, 0); } if (read.Content2.Length > 0) { read.Content2.CopyTo(result.Content, read.Content1.Length); } // string tmp2 = BasicFramework.SoftBasic.ByteToHexString( result.Content ) ; } else { IsSocketError = true; result.CopyErrorFromOther(read); } InteractiveLock.Leave( ); if (!IsPersistentConn) { resultSocket.Content?.Close( ); } return(result); }
/// <summary> /// 使用底层的数据报文来通讯,传入需要发送的消息,返回一条完整的数据指令 /// </summary> /// <param name="send">发送的完整的报文信息</param> /// <returns>接收的完整的报文信息</returns> public OperateResult <byte[]> ReadFromCoreServer(byte[] send) { var result = new OperateResult <byte[]>( ); // string tmp1 = BasicFramework.SoftBasic.ByteToHexString( send, '-' ); InteractiveLock.Enter( ); // 获取有用的网络通道,如果没有,就建立新的连接 OperateResult <Socket> resultSocket = GetAvailableSocket( ); if (!resultSocket.IsSuccess) { IsSocketError = true; if (AlienSession != null) { AlienSession.IsStatusOk = false; } InteractiveLock.Leave( ); result.CopyErrorFromOther(resultSocket); return(result); } OperateResult <byte[]> read = ReadFromCoreServer(resultSocket.Content, send); if (read.IsSuccess) { IsSocketError = false; result.IsSuccess = read.IsSuccess; result.Content = read.Content; // string tmp2 = BasicFramework.SoftBasic.ByteToHexString( result.Content ) ; } else { IsSocketError = true; if (AlienSession != null) { AlienSession.IsStatusOk = false; } result.CopyErrorFromOther(read); } InteractiveLock.Leave( ); if (!IsPersistentConn) { resultSocket.Content?.Close( ); } return(result); }
/// <summary> /// 新增账户,如果想要启动账户登录,比如将<see cref="IsUseAccountCertificate"/>设置为<c>True</c>。 /// </summary> /// <param name="userName">账户名称</param> /// <param name="password">账户名称</param> public void AddAccount(string userName, string password) { if (!string.IsNullOrEmpty(userName)) { lockLoginAccount.Enter( ); if (accounts.ContainsKey(userName)) { accounts[userName] = password; } else { accounts.Add(userName, password); } lockLoginAccount.Leave( ); } }
/// <summary> /// 获取自增信息 /// </summary> /// <returns>计数自增后的值</returns> public long GetCurrentValue( ) { long value = 0; hybirdLock.Enter( ); value = current; current += IncreaseTick; if (current > max) { current = start; } hybirdLock.Leave( ); return(value); }
private readonly SimpleHybirdLock dictLock; // dict词典的数据锁 #endregion #region JSON Object private void ParseFromRequest(byte[] data, DeviceRequest request) { foreach (var regular in request.RegularNodes) { var value = regular.GetValue(data, ByteTransform); jsonLock.Enter(); if (regular.RegularCode != RegularNodeTypeItem.StringAscii.Code && regular.RegularCode != RegularNodeTypeItem.StringUnicode.Code && regular.RegularCode != RegularNodeTypeItem.StringUtf8.Code && regular.TypeLength > 1) { // 数组 JObjectData[regular.Name] = new JArray(value); } else { // 单个的值 JObjectData[regular.Name] = new JValue(value); } jsonLock.Leave(); SetDictValue(regular.Name, value); WriteCustomerData?.Invoke(this, regular.Name); } }
private void TcpStateUpLine(AppSession state) { lockSessions.Enter( ); appSessions.Add(state); lockSessions.Leave( ); // 提示上线 ClientOnline?.Invoke(state); AllClientsStatusChange?.Invoke(ClientCount); // 是否保存上线信息 if (IsSaveLogClientLineChange) { LogNet?.WriteInfo(ToString( ), $"[{state.IpEndPoint}] Name:{ state?.LoginAlias } { StringResources.NetClientOnline }"); } }
private void TcpStateUpLine(AppSession state) { HybirdLockSockets.Enter( ); All_sockets_connect.Add(state); HybirdLockSockets.Leave( ); // 提示上线 ClientOnline?.Invoke(state); // 是否保存上线信息 if (IsSaveLogClientLineChange) { LogNet?.WriteInfo(ToString(), "IP:" + state.IpAddress + " Name:" + state?.LoginAlias + " " + StringResources.NetClientOnline); } // 计算客户端在线情况 AsyncCoordinator.StartOperaterInfomation( ); }
private SimpleHybirdLock hybirdLock = new SimpleHybirdLock( ); // 状态的锁 /// <summary> /// 新增一个文件的操作,仅仅是删除文件 /// </summary> /// <param name="action"></param> public void AddOperation(Action action) { hybirdLock.Enter( ); if (readStatus == 0) { // 没有读取状态,立马执行 action?.Invoke( ); } else { // 添加标记 queues.Enqueue(action); } hybirdLock.Leave( ); }
/// <summary> /// 在长连接模式下,断开服务器的连接,并切换到短连接模式 /// </summary> /// <returns>关闭连接,不需要查看IsSuccess属性查看</returns> /// <example> /// 直接关闭连接即可,基本上是不需要进行成功的判定 /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\Core\NetworkDoubleBase.cs" region="ConnectCloseExample" title="关闭连接结果" /> /// </example> public OperateResult ConnectClose( ) { OperateResult result = new OperateResult( ); isPersistentConn = false; InteractiveLock.Enter( ); // 额外操作 result = ExtraOnDisconnect(CoreSocket); // 关闭信息 CoreSocket?.Close( ); CoreSocket = null; InteractiveLock.Leave( ); LogNet?.WriteDebug(ToString( ), StringResources.NetEngineClose); return(result); }
private SimpleHybirdLock lock_trusted_clients; // 受信任的客户端的列表 /// <summary> /// 设置并启动受信任的客户端登录并读写,如果为null,将关闭对客户端的ip验证 /// </summary> /// <param name="clients">受信任的客户端列表</param> public void SetTrustedIpAddress(List <string> clients) { lock_trusted_clients.Enter( ); if (clients != null) { TrustedClients = clients.Select(m => { System.Net.IPAddress iPAddress = System.Net.IPAddress.Parse(m); return(iPAddress.ToString( )); }).ToList( ); IsTrustedClientsOnly = true; } else { TrustedClients = new List <string>( ); IsTrustedClientsOnly = false; } lock_trusted_clients.Leave( ); }
public static void Go() { Int32 x = 0; const Int32 iterations = 1000000; // about 14ms for ++ SimpleHybirdLock hybirdLock = new SimpleHybirdLock(); hybirdLock.Enter(); x++; hybirdLock.Leave(); Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i < iterations; i++) { hybirdLock.Enter(); i++; hybirdLock.Leave(); } //hybirdLock.Leave(); Console.WriteLine("Incrementing x in SimpleHybridLock: {0:N0}", sw.ElapsedMilliseconds); }
private void SetDictValue(string name, dynamic value) { dictLock.Enter(); if (dictDynamicValues.ContainsKey(name)) { dictDynamicValues[name] = value; } else { dictDynamicValues.Add(name, value); } dictLock.Leave(); }
/// <summary> /// 获取自增信息 /// </summary> /// <returns>计数自增后的值</returns> public long GetCurrentValue( ) { long value = 0; hybirdLock.Enter( ); value = current; current++; if (current > max) { current = 0; } hybirdLock.Leave( ); return(value); }
private SimpleHybirdLock readModbusLock; // 读取服务器数据时候的同步锁 #endregion #region Private Method private ushort GetMessageId() { ushort result = 0; simpleHybird.Enter(); result = messageId; if (messageId == ushort.MaxValue) { messageId = 0; } else { messageId++; } simpleHybird.Leave(); return(result); }
/// <summary> /// 获取当前文件的读写锁,如果没有会自动创建 /// </summary> /// <param name="filename">完整的文件路径</param> /// <returns>读写锁</returns> internal FileMarkId GetFileMarksFromDictionaryWithFileName(string filename) { FileMarkId fileMarkId = null; dict_hybirdLock.Enter( ); // lock operator if (m_dictionary_files_marks.ContainsKey(filename)) { fileMarkId = m_dictionary_files_marks[filename]; } else { fileMarkId = new FileMarkId(LogNet, filename); m_dictionary_files_marks.Add(filename, fileMarkId); } dict_hybirdLock.Leave( ); return(fileMarkId); }
/// <summary> /// 获取当前目录的读写锁,如果没有会自动创建 /// </summary> /// <param name="filePath">相对路径名</param> /// <returns>读写锁</returns> public GroupFileContainer GetGroupFromFilePath(string filePath) { GroupFileContainer GroupFile = null; hybirdLock.Enter( ); // lock operator if (m_dictionary_group_marks.ContainsKey(filePath)) { GroupFile = m_dictionary_group_marks[filePath]; } else { GroupFile = new GroupFileContainer(LogNet, filePath); m_dictionary_group_marks.Add(filePath, GroupFile); } hybirdLock.Leave( ); return(GroupFile); }
/// <summary> /// 使用用户自定义的解密方法从文件读取数据 /// </summary> /// <param name="decrypt">用户自定义的解密方法</param> /// Converter<string,string>代理表示字符串转字符串 比如有这个方法: //public string ConvertIntToString(int n) //{ // return n.ToString(); //} //这个方法是把整数转成字符串,所以可以这样写:Converter<int, string> convert = ConvertIntToString; //然后就可以这样调用: //string str = convert(100); public void LoadByFile(Converter <string, string> converter) { if (!FileSavePath.IsNullEmpty() && File.Exists(FileSavePath)) { HybirdLock.Enter(); try { using (StreamReader sr = new StreamReader(FileSavePath, Encoding.UTF8)) { LoadByString(converter(sr.ReadToEnd())); } } catch (Exception ex) { new LogHelper("SerialNumberBuilder类").WriteLog(ex); } finally { HybirdLock.Leave(); } } }
private bool disposedValue = false; // 要检测冗余调用 /// <summary> /// 释放当前的程序所占用的资源 /// </summary> /// <param name="disposing">是否释放资源</param> protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: 释放托管状态(托管对象)。 } // TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。 // TODO: 将大型字段设置为 null。 simpleHybird.Enter( ); appSessions.ForEach(m => m.WorkSocket?.Close( )); appSessions.Clear( ); simpleHybird.Leave( ); simpleHybird.Dispose( ); disposedValue = true; } }
private SimpleHybirdLock subcriptionHybirdLock; // 集合锁 /// <summary> /// 新增一个数据监视的任务,针对的是寄存器 /// </summary> /// <param name="monitor">监视地址对象</param> public void AddSubcription(ModBusMonitorAddress monitor) { subcriptionHybirdLock.Enter( ); subscriptions.Add(monitor); subcriptionHybirdLock.Leave( ); }