private void DoWork() { DxDebug.LogConsole("DNServer.DoWork():服务器线程启动!"); while (true) { _msgSemaphore.WaitOne(); Interlocked.Decrement(ref _curSemCount); while (true) { _cpuTime.WorkStart(); //时间分析计时 #if Multitask NetWorkMsg msg1 = _msgQueue.Dequeue(); NetWorkMsg msg2 = _msgQueue.Dequeue(); if (msg1 == null && msg2 == null) { break; } else if (msg1 != null && msg2 != null)//取到了两条消息 { //再消耗一条信号量 //_msgSemaphore.WaitOne(); Interlocked.Decrement(ref _curSemCount); Parallel.Invoke(delegate() { ProcessMsg(msg1); }, delegate() { ProcessMsg(msg2); }); } else if (msg1 != null && msg2 == null) { //只有一条消息,就直接执行 ProcessMsg(msg1); } else if (msg1 == null && msg2 != null) { //只有一条消息,就直接执行 ProcessMsg(msg2); } #else NetWorkMsg msg = _msgQueue.Dequeue(); if (msg == null) //直到消息取尽之前都不停的处理 { break; } float waitTime = (DateTime.Now.Ticks - msg.timeTickCreat) / 10000;//毫秒 if (waitTime > _warringWaitTime) { _warringWaitTime += 500; DxDebug.LogWarning("DNServer.DoWork():NetWorkMsg等待处理时间过长!waitTime:" + waitTime); } else if ((_warringWaitTime - waitTime) > 500) { _warringWaitTime -= 500; } ProcessMsg(msg); #endif _cpuTime.WaitStart(); //时间分析计时 } } }
/// <summary> /// 指定目录创建日志文件(输入文件夹路径) /// </summary> /// <param name="folderPath">文件夹路径</param> /// <param name="isClearFolder">是否清除较早的日志文件</param> /// <param name="day">清除天数</param> public void CreatLogFile(string folderPath, bool isClearFolder = true, float day = 3.0f) { if (string.IsNullOrEmpty(folderPath)) { return; } lock (_lockFile) { //如果有资源就释放 Close(); try { //检查路径是文件还是目录 FileInfo fileInfo = new FileInfo(folderPath); if (fileInfo.Exists) //如果这玩意已经是个文件 { this.folderPath = fileInfo.DirectoryName; //把路径设置为该文件的所属文件夹 } else { DirectoryInfo dirInfo = new DirectoryInfo(folderPath); if (!dirInfo.Exists) { Directory.CreateDirectory(dirInfo.FullName); } this.folderPath = dirInfo.FullName; } //清理日志文件夹 if (isClearFolder) { ClearLogFileInFolder(this.folderPath, day); } string time = string.Format(@"[{0:D2}.{1:D2}][{2:D2}-{3:D2}-{4:D2}]", DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second); _fileStream = new FileStream(Path.Combine(this.folderPath, time + programName + fileExtension), FileMode.Create); _streamWriter = new StreamWriter(_fileStream, Encoding.UTF8, 1024); _streamWriter.AutoFlush = false; //创建定时器 _timer = new Timer(new TimerCallback(OnTimerTick)); _timer.Change(250, 5000); while (_tempString != null && _tempString.Count > 0)//如果已经记录有内容 { string item = _tempString.Dequeue(); _streamWriter.WriteLine(item); _streamWriter.Flush(); } _tempString.TrimExcess();//不再使用了 } catch (Exception) { Close(); } } }
/// <summary> /// 线程的工作函数 /// </summary> private void DoWork() { DxDebug.LogConsole("WorkThread.DoWork():工作线程启动!"); while (_isRun) { IWorkMsg msg = null; try { //记录线程空闲 RecThreadStatus(Thread.CurrentThread.ManagedThreadId, false); _msgSemaphore.WaitOne(); Interlocked.Decrement(ref _curSemCount); //记录线程开始工作 RecThreadStatus(Thread.CurrentThread.ManagedThreadId, true); while (true) { msg = _msgQueue.Dequeue(); if (msg != null) { //递增计数 Interlocked.Increment(ref _procMsgCount); try { //取一条消息进行执行 msg.DoWork(); } catch (Exception e) { DxDebug.LogWarning("WorkThread.DoWork():执行msg异常:" + msg.Name + "异常信息:" + e.Message); } } else { break; } } } catch (Exception e) { if (msg != null) { DxDebug.LogError("WorkThread.DoWork():异常:" + msg.Name + "异常信息:" + e.Message); } else { DxDebug.LogError("WorkThread.DoWork():异常:目前IWorkMsg为null(可能空闲),异常信息:" + e.Message); } } } }
/// <summary> /// 连接服务器,输入IP和端口号。会强制重新初始化整个类,这样起到底层重启的作用。 /// </summary> /// <param name="host">主机IP</param> /// <param name="port">端口号</param> public void Connect(string host, int port) { try { DxDebug.LogConsole("DNClient.Connect():连接服务器 主机:" + host + " 端口:" + port); //标记正在连接 IsConnecting = true; //if (_disposed) //{ // DxDebug.LogConsole("DNClient.Connect():这个类对象是被释放状态,重新初始化"); Init(); //} //进行一次连接的时候,把消息队列清空 Clear(); Interlocked.Exchange(ref this._host, host); //给类成员赋值 Interlocked.Exchange(ref this._port, port); //给类成员赋值 NetWorkMsg msg = _msgPool.Dequeue(); if (msg == null) { msg = new NetWorkMsg(NetWorkMsg.Tpye.C_Connect); } else { msg.Reset(NetWorkMsg.Tpye.C_Connect); } AddMessage(msg); LastMsgReceTickTime = DateTime.Now.Ticks; LastMsgSendTickTime = DateTime.Now.Ticks; } catch (Exception e) { IsConnecting = false;//连接失败了 DxDebug.LogError("DNClient.Connect():异常:" + e.Message); if (EventError != null) { try { EventError(this, EventType.ConnectError, e);//事件类型:ConnectError } catch (Exception e2) { DxDebug.LogWarning("DNClient.Connect():执行EventError事件异常:" + e2.Message); } } Dispose();//释放 } }
/// <summary> /// 往内存日志队列添加一行日志 /// </summary> /// <param name="pri">优先级</param> /// <param name="msg">日志内容</param> private static LogItem AddMemLog(int pri, ref string msg) { lock (_lockMem) { if (_logQueue.Count < MAX_LENGTH) { LogItem log = new LogItem() { priority = pri, message = msg }; _logQueue.Enqueue(log); return(log); } else { LogItem log = _logQueue.Dequeue(); log.priority = pri; log.message = msg; _logQueue.Enqueue(log); return(log); } } }
private void DoWork() { try { DxDebug.LogConsole("DNClient.DoWork():-----------通信线程启动!"); while (true) { Interlocked.Exchange(ref _isThreadWorking, 0);//标记当前线程已经停止工作 _msgSemaphore.WaitOne(); Interlocked.Decrement(ref _curSemCount); //递减信号量计数 Interlocked.Exchange(ref _isThreadWorking, 1); //标记当前线程已经正在执行工作 //_cpuTime.WorkStart(); //时间分析计时 while (true) { NetWorkMsg msg = _msgQueue.Dequeue(); if (msg == null) { break; } float waitTime = (DateTime.Now.Ticks - msg.timeTickCreat) / 10000;//毫秒 if (waitTime > _warringWaitTime) { _warringWaitTime += 500; DxDebug.LogWarning("DNClient.DoWork():NetWorkMsg等待处理时间过长!waitTime:" + waitTime); } else if ((_warringWaitTime - waitTime) > 500) { _warringWaitTime -= 500; } if (msg != null) { switch (msg.type) { case NetWorkMsg.Tpye.C_Connect: DoConnect(); break; case NetWorkMsg.Tpye.C_Send: DoSend(msg); break; case NetWorkMsg.Tpye.C_Receive: DoReceive(); break; case NetWorkMsg.Tpye.C_AsynClose: DoClose(); _workThread = null; //把这个成员置为空 return; //执行完就结束了整个线程函数 default: break; } //用过的消息放回池里 _msgPool.EnqueueMaxLimit(msg); } else { // _cpuTime.Calculate();//空闲的话就计算一下 } //long costTime = _cpuTime.WaitStart(); //时间分析计时 } } } catch (Exception e) { DxDebug.LogError("DNClient.DoWork():异常:通信线程执行异常! " + e.Message); } }