ScanBuffer.cs 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. namespace BeiJingComService.Core
  3. {
  4. /// <summary>
  5. /// 扫码预捕获缓冲(Round54)。
  6. ///
  7. /// 只保留「最近一次」扫码结果,带 TTL,取走即清空。
  8. /// 用途:患者选完电子凭证就开始扫,而扫码窗还没弹出来,这段里扫到的码会丢失。
  9. /// 本缓冲把它接住,业务侧弹窗后主动取走。
  10. ///
  11. /// 安全约束(硬性):
  12. /// · 码内容是医保电子支付凭证,等价于支付凭证,<b>绝不写日志、绝不落盘、绝不进调试页</b>;
  13. /// · 只存在于本进程内存,进程退出即消失。
  14. /// </summary>
  15. internal static class ScanBuffer
  16. {
  17. private static readonly object _sync = new object();
  18. private static string _value;
  19. private static long _pushedAtMs;
  20. private static int _ttlMs = 5000;
  21. /// <summary>
  22. /// 统一时间源(毫秒,单调递增),钩子与缓冲共用,避免两套时钟。
  23. /// 用 Stopwatch 而不是 Environment.TickCount64 —— 后者在 .NET Framework 里不存在(CS0117)。
  24. /// </summary>
  25. internal static long NowMs()
  26. {
  27. return (long)(System.Diagnostics.Stopwatch.GetTimestamp() * 1000.0
  28. / System.Diagnostics.Stopwatch.Frequency);
  29. }
  30. /// <summary>注入 TTL(毫秒)。非正数忽略,保留默认 5000。</summary>
  31. internal static void Configure(int ttlMs)
  32. {
  33. if (ttlMs > 0) { _ttlMs = ttlMs; }
  34. }
  35. internal static int TtlMs
  36. {
  37. get { return _ttlMs; }
  38. }
  39. /// <summary>
  40. /// 写入最近一次扫码结果。覆盖式:新码直接盖掉旧码。
  41. /// </summary>
  42. internal static void Push(string code, long atMs)
  43. {
  44. if (string.IsNullOrEmpty(code)) { return; }
  45. lock (_sync)
  46. {
  47. _value = code;
  48. _pushedAtMs = atMs;
  49. }
  50. }
  51. /// <summary>
  52. /// 取走并清空。命中返回 true 并给出码与已存活时长;过期按未命中处理并清空。
  53. /// 同一个码绝不会被取到第二次。
  54. /// </summary>
  55. internal static bool TryTake(out string code, out int ageMs)
  56. {
  57. code = null;
  58. ageMs = -1;
  59. lock (_sync)
  60. {
  61. if (_value == null) { return false; }
  62. long age = NowMs() - _pushedAtMs;
  63. if (age < 0) { age = 0; } // 极端情况(时钟异常)兜底
  64. if (age > _ttlMs)
  65. {
  66. // 过期即丢弃:避免上一个人留下的码被下一个人捡走
  67. _value = null;
  68. return false;
  69. }
  70. code = _value;
  71. _value = null; // 消费即清:一码一用
  72. ageMs = (int)age;
  73. return true;
  74. }
  75. }
  76. /// <summary>仅诊断用:当前缓冲是否有值(不取走、不返回内容)。</summary>
  77. internal static bool HasValue
  78. {
  79. get
  80. {
  81. lock (_sync) { return _value != null; }
  82. }
  83. }
  84. }
  85. }