| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- using System;
- namespace BeiJingComService.Core
- {
- /// <summary>
- /// 扫码预捕获缓冲(Round54)。
- ///
- /// 只保留「最近一次」扫码结果,带 TTL,取走即清空。
- /// 用途:患者选完电子凭证就开始扫,而扫码窗还没弹出来,这段里扫到的码会丢失。
- /// 本缓冲把它接住,业务侧弹窗后主动取走。
- ///
- /// 安全约束(硬性):
- /// · 码内容是医保电子支付凭证,等价于支付凭证,<b>绝不写日志、绝不落盘、绝不进调试页</b>;
- /// · 只存在于本进程内存,进程退出即消失。
- /// </summary>
- internal static class ScanBuffer
- {
- private static readonly object _sync = new object();
- private static string _value;
- private static long _pushedAtMs;
- private static int _ttlMs = 5000;
- /// <summary>
- /// 统一时间源(毫秒,单调递增),钩子与缓冲共用,避免两套时钟。
- /// 用 Stopwatch 而不是 Environment.TickCount64 —— 后者在 .NET Framework 里不存在(CS0117)。
- /// </summary>
- internal static long NowMs()
- {
- return (long)(System.Diagnostics.Stopwatch.GetTimestamp() * 1000.0
- / System.Diagnostics.Stopwatch.Frequency);
- }
- /// <summary>注入 TTL(毫秒)。非正数忽略,保留默认 5000。</summary>
- internal static void Configure(int ttlMs)
- {
- if (ttlMs > 0) { _ttlMs = ttlMs; }
- }
- internal static int TtlMs
- {
- get { return _ttlMs; }
- }
- /// <summary>
- /// 写入最近一次扫码结果。覆盖式:新码直接盖掉旧码。
- /// </summary>
- internal static void Push(string code, long atMs)
- {
- if (string.IsNullOrEmpty(code)) { return; }
- lock (_sync)
- {
- _value = code;
- _pushedAtMs = atMs;
- }
- }
- /// <summary>
- /// 取走并清空。命中返回 true 并给出码与已存活时长;过期按未命中处理并清空。
- /// 同一个码绝不会被取到第二次。
- /// </summary>
- internal static bool TryTake(out string code, out int ageMs)
- {
- code = null;
- ageMs = -1;
- lock (_sync)
- {
- if (_value == null) { return false; }
- long age = NowMs() - _pushedAtMs;
- if (age < 0) { age = 0; } // 极端情况(时钟异常)兜底
- if (age > _ttlMs)
- {
- // 过期即丢弃:避免上一个人留下的码被下一个人捡走
- _value = null;
- return false;
- }
- code = _value;
- _value = null; // 消费即清:一码一用
- ageMs = (int)age;
- return true;
- }
- }
- /// <summary>仅诊断用:当前缓冲是否有值(不取走、不返回内容)。</summary>
- internal static bool HasValue
- {
- get
- {
- lock (_sync) { return _value != null; }
- }
- }
- }
- }
|