You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何对native sized integer执行Interlocked增减操作?

对原生大小整数执行Interlocked增减操作的方法

C# 9.0引入的nint/nuint(原生大小整数)确实没有直接对应的Interlocked.Increment()或Interlocked.Decrement()重载,但可以通过以下方式实现原子增减:

1. 用Interlocked.Add()模拟增减操作

这是适配所有支持原生大小整数的.NET版本的通用方案:

  • 递增操作:对nint变量调用Interlocked.Add(ref 变量, 1),返回值即为递增后的结果,和Increment()行为完全一致;对nuint变量则调用Interlocked.Add(ref 变量, 1)即可。
  • 递减操作:对nint变量调用Interlocked.Add(ref 变量, -1);对nuint变量,利用无符号整数的合法溢出特性,调用Interlocked.Add(ref 变量, nuint.MaxValue)即可模拟减1效果。

示例代码:

// nint的原子递增
nint intCount = 0;
nint newIntValue = Interlocked.Add(ref intCount, 1);

// nuint的原子递减
nuint uintCount = 100;
nuint newUintValue = Interlocked.Add(ref uintCount, nuint.MaxValue);

2. .NET 6及以上版本直接使用重载方法

从.NET 6开始,Interlocked类新增了针对nint和nuint的Increment()、Decrement()重载,直接调用即可:

nint count = 0;
nint incremented = Interlocked.Increment(ref count);
nint decremented = Interlocked.Decrement(ref count);

内容的提问来源于stack exchange,提问作者owacoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 21:55:07