private void TimerAction(object o) { var tc = DateTime.Now; try { _backtimer.Change(Timeout.Infinite, Timeout.Infinite); if (_queueWriter != null && !this._isdispose) { _queueWriter.Flush(); } if (!IsRuning && _queueReader != null) { new Action(ProcessQueue).BeginInvoke(null, null); } SaveConfig(); } finally { _backtimer.Change((int)Math.Max(1000 - (DateTime.Now.Subtract(tc)).TotalMilliseconds, 0), 0); } }
public LocalFileQueue(string queuename, string queuefilepath, bool canwrite = true, bool canread = true) { if (string.IsNullOrWhiteSpace(queuename)) { throw new ArgumentNullException("queuename"); } QueueName = queuename; if (string.IsNullOrWhiteSpace(queuefilepath)) { throw new ArgumentNullException("queuefilepath"); } QueueFilePath = queuefilepath; if (!File.Exists(queuefilepath)) { FileInfo file = new FileInfo(queuefilepath); if (!file.Directory.Exists) { try { file.Directory.Create(); } catch (Exception ex) { throw new Exception("创建文件夹失败:" + file.Directory.FullName, ex); } } } if (canwrite) { //由于文件写是独占式的,当程序快速重启时,文件可能未及时释放 int trytimes = 0; while (true) { try { //_queueWriter = ObjTextWriter.CreateWriter(queuefilepath, ObjTextReaderWriterEncodeType.jsonbuf); _queueWriter = ObjTextWriter.CreateWriter(queuefilepath, ObjTextReaderWriterEncodeType.entitybuf); _queueWriter.Flush(); break; } catch (Exception ex) { trytimes++; if (trytimes >= 3) { throw ex; } Thread.Sleep(1000 * trytimes); } } } if (canread) { while (true) { if (File.Exists(queuefilepath)) { break; } Thread.Sleep(1000); } _queueReader = ObjTextReader.CreateReader(queuefilepath); FileInfo finfo = new FileInfo(queuefilepath); QueueCfgFile = finfo.Directory.FullName + "\\" + queuename + ".cfg"; if (File.Exists(QueueCfgFile)) { _logger = LJC.FrameWork.Comm.SerializerHelper.DeSerializerFile <LocalFileQueueCfg>(QueueCfgFile, true); if (_logger.LastPos > 0) { _queueReader.SetPostion(_logger.LastPos); } } else { _logger = new LocalFileQueueCfg(); _logger.LastChageTime = DateTime.Now; _logger.QueueFile = queuefilepath; SaveConfig(); } } _backtimer = new Timer(new TimerCallback(TimerAction), null, 0, 0); }