I'm wondering if there's an inbuilt collection (or any way to make a custom one) in C# that can be used to emit numbers in a rotating/cyclic fashion (see example below), and is thread-safe (so each thread gets the next number in the collection).
Collection with 5 sequential numbers: Thread 1 read: return value 1 Thread 2 read: return value 2 Thread 3 read: return value 3 Thread 4 read: return value 4 Thread 5 read: return value 5 Thread 6 read: return value 1 Thread 7 read: return value 2 Thread 8 read: return value 3
and so on.
Basically, the next number emitted by the collection (when read by a thread) should be one after the previous one, and it should restart from the beginning at the end of the number set.
You can greate a method, that will return infinate enumerable:
private object _lock = new object();
private int i = 0;
private int max = 6;
public IEnumerable<int> GetNumbers()
{
while (true)
{
lock (_lock)
{
i++;
if (i == max)
i = 1;
yield return i;
}
}
}
And get them:
var numbers = GetNumbers().Take(1000).ToArray();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.