我正在寻找一些关于编写一些线程安全,优化,优雅的代码的建议来执行以下操作:
我想要一个静态方法来返回一个整数序列。因此,例如,应用程序启动,线程1调用GetSequence方法并表示它想要取3,因此它得到一个由0,1,2组成的整数数组。线程2然后调用该方法并说给我4,所以它返回3,4,5,6。多个线程可以同时调用此方法。
为了了解我正在考虑的事情,这是我对此的尝试:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SequenceNumberService
{
class Program
{
static void Main(string[] args)
{
int[] numbers = NumberSequenceService.GetSequence(3);
foreach (var item in numbers)
{
Console.WriteLine(item.ToString());
}
// Writes out:
// 0
// 1
// 2
Console.ReadLine();
}
}
public static class NumberSequenceService
{
private static int m_LastNumber;
private static object m_Lock = new Object();
public static int[] GetSequence(int take)
{
int[] returnVal = new int[take];
int lastNumber;
// Increment the last audit number, based on the take value.
// It is here where I am concerned that there is a threading issue, as multiple threads
// may hit these lines of code at the same time. Should I just put a lock around these two lines
// of code, or is there a nicer way to achieve this.
lock (m_Lock)
{
m_LastNumber = m_LastNumber + take;
lastNumber = m_LastNumber;
}
for (int i = take; i > 0; i--)
{
returnVal[take - i] = lastNumber - i;
}
return returnVal;
}
}
}
我的问题是: 我是以最好的方式接近这个,还是有另一种方法来实现这一目标? 有关优化此代码的任何建议吗?
非常感谢您的任何帮助。
答案 0 :(得分:7)
您可能希望查看Interlocked课程及其Increment和Add方法:
public static Int32 num = 0;
public static Int32 GetSequence()
{
return Interlocked.Increment(ref num);
}
public static IEnumerable<Int32> GetSequenceRange(Int32 count)
{
var newValue = Interlocked.Add(ref num, count);
return Enumerable.Range(newValue - count, count);
}