Parallel.For para não usar o meu thread principal
No meu aplicativo, quero que meu thread principal não seja usado por mais nada. Eu tenho que fazer algum processamento paralelo que gostaria de ser feito por diferentes threads. Para isso, estou usando Parallel.For da seguinte maneira
static void SomeMethod()
{
Console.WriteLine(string.Format("Main Thread ID before parallel loop ->>>>>>> {0} ", System.Threading.Thread.CurrentThread.ManagedThreadId));
Parallel.For(0, 10, i =>
{
Console.WriteLine(string.Format("Output ->>>>>>> {0} ", System.Threading.Thread.CurrentThread.ManagedThreadId));
});
Thread.Sleep(100);
Console.WriteLine(string.Format("Main Thread ID after parallel loop ->>>>>>> {0} ", System.Threading.Thread.CurrentThread.ManagedThreadId));
}
Como você pode ver no thread principal de saída, está usando o ThreadID 1 e alguns threads do Parallel.For também estão usando o mesmo thread.
Main Thread ID before parallel loop ->>>>>>> 1
Output ->>>>>>> 1
Output ->>>>>>> 1
Output ->>>>>>> 3
Output ->>>>>>> 4
Output ->>>>>>> 4
Output ->>>>>>> 4
Output ->>>>>>> 4
Output ->>>>>>> 5
Output ->>>>>>> 3
Output ->>>>>>> 1
Main Thread ID after parallel loop ->>>>>>> 1
Existe alguma maneira de garantir que algo em Parallel.For sempre seja executado em um thread separado para que o thread principal esteja sempre livre.