首页 > 代码库 > 多线程下操作数字要用类System.Threading.Interlocked

多线程下操作数字要用类System.Threading.Interlocked

public class ServiceStatistics
{
private int _sourseCount = 0;
/// <summary>
/// 处理源数据量
/// </summary>
public int SourseCount
{
get { return _sourseCount; }
}
private int _destinationCount = 0;
/// <summary>
/// 返回结果数据量
/// </summary>
public int DestinationCount
{
get { return _destinationCount; }
}

private long _elapsedMilliseconds = 0L;
/// <summary>
/// 执行耗时
/// </summary>
public long ElapsedMilliseconds
{
get { return _elapsedMilliseconds; }
}
/// <summary>
/// 增加源数据量
/// </summary>
/// <param name="count"></param>
public void IncrementSourse(int count = 1)
{
if (count < 1)
return;
System.Threading.Interlocked.Add(ref _sourseCount, count);
}
/// <summary>
/// 增加结果数据量
/// </summary>
/// <param name="count"></param>
public void IncrementDestination(int count = 1)
{
if (count < 1)
return;
System.Threading.Interlocked.Add(ref _destinationCount, count);
}
/// <summary>
/// 增加执行耗时
/// </summary>
/// <param name="milliseconds"></param>
public void Elapsed(long milliseconds)
{
if (milliseconds < 1L)
return;
System.Threading.Interlocked.Add(ref _elapsedMilliseconds, milliseconds);
}

 

多线程下操作数字要用类System.Threading.Interlocked