最佳线程安全的方式来增加一个整数高达65535 [英] Best thread-safe way to increment an integer up to 65535

查看:136
本文介绍了最佳线程安全的方式来增加一个整数高达65535的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个递增计数器,每3秒System.Timers.Timer。另一个线程也可以将此变量设置为某些情况下的任何值。



试过使用 Interlocked.Increment ,但它不具备过载UINT16。考虑到接下来的事情就是,但我真的不知道如何使线程安全存取(读/写/增量)这个变量。



编辑:该代码最初使用int,但改为UINT16的建议

 私人挥发性System.UInt16形式mCounter = 0; 
私人只读对象mCounterLock =新的对象();
公共System.UInt16形式计数器{
获得{
锁(mCounterLock){
返回mCounter;
}
}
集合{
锁(mCounterLock){
mCounter =价值;
}
}
}
私人System.Timers.Timer mCounterTimer;

无效mCounter_Elapsed(对象发件人,System.Timers.ElapsedEventArgs E){
锁(mCounterLock){
计数器++;
}
}


解决方案

刚改变你的Int32值Int16的,如果你只需要2个字节。由于夏嘉曦去除这里他的答案是一些代码



  UINT16设为myVal = 0; 
对象myvalLock =新的对象();
....
锁(myvalLock){++设为myVal; }


I have a System.Timers.Timer that increments a counter every 3 seconds. Another thread may also set this variable to any value under some conditions.

Tried to use Interlocked.Increment but it does not have an overload for UInt16. The next thing in mind is lock, but I am not really sure how to make thread-safe access (read/write/increment) to this variable.

Edited: the code originally used an int, but changed to UInt16 as suggested

private volatile System.UInt16 mCounter = 0;
private readonly object mCounterLock = new object();
public System.UInt16 Counter {
  get {
    lock (mCounterLock) {
      return mCounter;
    }
  }
  set {
    lock (mCounterLock) {
      mCounter = value;
    }
  }
}
private System.Timers.Timer mCounterTimer;

void mCounter_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
  lock (mCounterLock) {
    Counter++;
  }
}

解决方案

Just change your Int32 value to Int16 if you only need 2 bytes. Since Shai removed his answer here's some code

UInt16 myval = 0;
Object myvalLock = new Object();
....
lock (myvalLock) { myval++; }

这篇关于最佳线程安全的方式来增加一个整数高达65535的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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