Parallel.For not to use my main thread

自古美人都是妖i 提交于 2019-11-28 12:49:53

Is there some way to make sure that anything in Parallel.For always run on separate thread so that main thread is always free.

Parallel.For will always block until everything is finished - so even if it didn't do anything on the original thread, the thread still wouldn't be "free".

If you want to keep the main thread "free" you might want to look into async and await - you could use Task.Run to start the 10 tasks in an async method, and then await the result of calling Task.WhenAll.

Alternatively, you could still use Parallel.For but do that in a task. For example:

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

You could then await that task. The "main thread" of the task will probably be used in the Parallel.For loop, but that's okay because it's still not your original main thread, if you see what I mean.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!