Можно ли внутри Semaphore использовать lock?
Я написал следующий код:
public class WorkerQueue<T>
{
private readonly List<T> _resource = new();
private readonly Semaphore _semaphore = new(5, 10);
public void AddItem(T item)
{
Console.WriteLine($"Поток {Thread.CurrentThread.Name} готов добавить элемент");
_semaphore.WaitOne();
try
{
lock (_resource)
{
_resource.Add(item);
}
}
finally
{
Console.WriteLine($"Поток {Thread.CurrentThread.Name} добавил элемент");
_semaphore.Release();
}
}
public int GetCountItems()
{
return _resource.Count();
}
public IEnumerable<T> GetItems()
{
return _resource.OrderBy(x=>x);
}
}
public class Program
{
private static List<Thread> _threads = new();
private static WorkerQueue<int> _worker = new();
static void Main(string[] args)
{
for (int i = 1; i <= 6; i++)
{
Thread thread = new(ThreadProc);
thread.Name = i.ToString();
thread.Start();
}
Console.ReadLine();
int count = _worker.GetCountItems();
var items = _worker.GetItems().GroupBy(x=>x)
.Select(x=> new
{
Key = x.Key,
Count = x.Count()
}).Where(x=> x.Count != 6);
}
private static void ThreadProc()
{
for (int i = 0; i < 100000; i++)
{
_worker.AddItem(i);
}
}
}
Я здесь использую lock так как внутри Semaphore к моему ресурсу будет одновременно обращаться 5 потоков, что приведёт к тому, что у меня в списке будут неполные данные. Но есть подозрения, что тогда тут Semaphore и не нужен вообще)