Windows/C#系统级序号生成器?

编程入门 行业动态 更新时间:2024-10-26 14:40:57
本文介绍了Windows/C#系统级序号生成器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否存在托管系统级序号生成器? DateTime.Now.Ticks不会执行,因为我正在执行的操作有时每个刻度会发生一次以上.

Is there a managed system-level sequential number generator? DateTime.Now.Ticks won't do because the operations I'm doing sometimes occur more than once per tick.

要求说明:

  • 不可知的过程-实际上只有一个过程可以访问此过程.
  • 性能至关重要!这用于记录广告服务器上的展示次数,最高可以达到1k/秒

它必须是以下之一:

  • 一个4字节的序号,它会重置每个刻度线
  • 一个12字节的序号-实际上将4个字节的粒度添加到DateTime中
推荐答案

无此目的,但是您可以使用 System.Diagnostics.PerformanceCounter .您也可以使用注册表,但需要在整个过程中序列化读/写访问权限.

None that are intended for this, but you could use System.Diagnostics.PerformanceCounter. You could also use the Registry but you'd need to serialize read/write access accross the processes.

System.Diagnostics.PerformanceCounter pc = new System.Diagnostics.PerformanceCounter("SeqCounter", "SeqInstance"); long myVal=pc.Increment();

编辑

我对此的思考越多,我认为这可能是一个不错的解决方案.增量将通过原子操作将计数器增加1,该操作应在系统上的所有进程中起作用.

Edit

The more I think about this, I think this could be a nice solution. Increment will increase the counter by 1 through an atomic operation which should work accross all processes on a system.

根据您的修改,我建议您不要使用效果计数器.性能计数器是协调多个流程的一种方式.我不确定内部实现的编码方式.

Based on your edits, I would not recommend using a performance counter. A performance counter was a way to cordinate accross multiple processes. I am not sure how the internal implemention is coded.

为什么不能只使用静态变量并将其递增?如果您希望某些东西是线程安全的,则必须将其锁定.

Why can't you just use a static variable and increment it? Your going to have to lock something if you want this to be threadsafe.

System.Threading.Interlocked.Increment

仅供参考:如果您在32位系统上使用长版,则不会确保线程安全.

FYI: If you use the long version on a 32 bit system it won't nessecarilly be thread safe.

编辑以显示我使用的实现(DS):

Editing to show the implemention I used (DS):

public static class Int32Sequencer { private static Int32 lastSequence = Int32.MinValue; private static Object lockObject = new Object(); public static Int32 GetNextSequence() { lock (lockObject) { unchecked { lastSequence++; } return lastSequence; } } }

更多推荐

Windows/C#系统级序号生成器?

本文发布于:2023-11-10 09:23:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574990.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:生成器   序号   系统   Windows

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!