Parallel. Do not use my main thread

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.

+3
source share
1 answer

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.

Parallel.For , - , , "".

, "", async - Task.Run 10 , await Task.WhenAll.

Parallel.For, . :

Task task = Task.Run(() => Parallel.For(0, 10, i =>
{
    Console.WriteLine("Output ->>>>>>> {0} ", 
                      Thread.CurrentThread.ManagedThreadId);
}));

. " " , , Parallel.For, , - , , .

+7

Source: https://habr.com/ru/post/1625737/


All Articles