I'm newbie to use threading logic.
I declared ThreadPool.SetMaxThreads(10, 10) and create multiple thread same number of 10.
First request working well, I requested 2 more each different browser. following request fallen hang until finish first request's thread work.
Does ThreadPool.SetMaxThreads affected entire IIS application pool?
public ActionResult Index()
{
ThreadPool.SetMaxThreads(10, 10);
for (int i = 0; i < 10; i++)
{
Task.Factory.StartNew(() =>
{
try
{
Thread.Sleep(30000);
}
finally
{
}
});
}
return View();
}
Here's new code using semaphoreslim. My Actual goal is only specified count of threads run at once. for example I will download 9 files and assign each thread 1 download job, max 3 threads work.
public ActionResult Index()
{
int maxConcurrency = 3;
using (SemaphoreSlim concurrencySemaphore = new SemaphoreSlim(maxConcurrency))
{
List<Task> tasks = new List<Task>();
for (int i = 0; i < 9; i++)
{
concurrencySemaphore.Wait();
var t = Task.Factory.StartNew(() =>
{
try
{
// Here to actual my job logic.
Thread.Sleep(10000);
}
finally
{
concurrencySemaphore.Release();
}
});
tasks.Add(t);
}
Task.WaitAll(tasks.ToArray());
}
return View();
}