C#线程安全快速(EST)计数器 [英] C# Thread safe fast(est) counter

查看:158
本文介绍了C#线程安全快速(EST)计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是获得在C#中的线程安全的计数器,具有最佳性能的方式。

What is the way to obtain a thread safe counter in C# with best possible performance?

这很简单,因为它得到:

This is as simple as it gets:

public static long GetNextValue()
{
    long result;
    lock (LOCK)
    {
        result = COUNTER++;
    }
    return result;
}



但是否有更快的办法?

But are there faster alternatives?

推荐答案

这是简单的:

return Interlocked.Increment(ref COUNTER);

MSDN Interlocked.Increment

这篇关于C#线程安全快速(EST)计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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