Windows/C#系统级序号生成器? [英] Windows/C# system-level sequential number generator?

查看:134
本文介绍了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#系统级序号生成器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆