In my application, I want my main thread not to be used by anything else. I have to do some parallel processing, which I would like to do with different threads. For this, I use Parallel.For as follows
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));
}
As you can see from the main output thread, ThreadID 1 is used, and some threads from Parallel.For also use the same 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
Is there a way to make sure that something in Parallel.For always runs in a separate thread, so that the main thread is always free.
source
share