FileMarkId.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using HslCommunication.Core;
  2. using HslCommunication.LogNet;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. namespace HslCommunication.Enthernet
  8. {
  9. /// <summary>
  10. /// 文件标记对象类
  11. /// </summary>
  12. internal class FileMarkId
  13. {
  14. /// <summary>
  15. /// 实例化一个文件标记对象
  16. /// </summary>
  17. public FileMarkId( ILogNet logNet, string fileName )
  18. {
  19. LogNet = logNet;
  20. FileName = fileName;
  21. }
  22. private ILogNet LogNet; // 日志
  23. private string FileName = null; // 文件名称
  24. private Queue<Action> queues = new Queue<Action>( ); // 操作的队列
  25. private SimpleHybirdLock hybirdLock = new SimpleHybirdLock( ); // 状态的锁
  26. /// <summary>
  27. /// 新增一个文件的操作,仅仅是删除文件
  28. /// </summary>
  29. /// <param name="action"></param>
  30. public void AddOperation( Action action )
  31. {
  32. hybirdLock.Enter( );
  33. if (readStatus == 0)
  34. {
  35. // 没有读取状态,立马执行
  36. action?.Invoke( );
  37. }
  38. else
  39. {
  40. // 添加标记
  41. queues.Enqueue( action );
  42. }
  43. hybirdLock.Leave( );
  44. }
  45. private int readStatus = 0;
  46. /// <summary>
  47. /// 指示该对象是否能被清除
  48. /// </summary>
  49. /// <returns></returns>
  50. public bool CanClear( )
  51. {
  52. bool result = false;
  53. hybirdLock.Enter( );
  54. result = readStatus == 0 && queues.Count == 0;
  55. hybirdLock.Leave( );
  56. return result;
  57. }
  58. /// <summary>
  59. /// 进入文件的读取状态
  60. /// </summary>
  61. public void EnterReadOperator( )
  62. {
  63. hybirdLock.Enter( );
  64. readStatus++;
  65. hybirdLock.Leave( );
  66. }
  67. /// <summary>
  68. /// 离开本次的文件读取状态
  69. /// </summary>
  70. public void LeaveReadOperator( )
  71. {
  72. // 检查文件标记状态
  73. hybirdLock.Enter( );
  74. readStatus--;
  75. if (readStatus == 0)
  76. {
  77. while (queues.Count > 0)
  78. {
  79. try
  80. {
  81. queues.Dequeue( )?.Invoke( );
  82. }
  83. catch (Exception ex)
  84. {
  85. LogNet?.WriteException( "FileMarkId", "File Action Failed:", ex );
  86. }
  87. }
  88. }
  89. hybirdLock.Leave( );
  90. }
  91. }
  92. }