I am trying to make some code run multithreaded using SemaphoreSlim
and Task.Run()
.
Here is the snippet:
var semaphore = new SemaphoreSlim(50, 50);
foreach (var item in collection)
{
semaphore.Wait();
Task.Run(() =>
{
item.Property = DoTheThing(item.AnotherValue).Result;
db.SaveChanges();
semaphore.Release();
});
}
What I expected to happen is that 50 tasks would be queued up and then semaphore.Wait()
would kick in and hold the foreach loop until some tasks complete and semaphore.Release()
frees up the threads so more can be queued.
What actually happens is the code runs synchronously one after the other. What am I missing here? I thought Task.Run()
launched the lambda code on a new thread?