Parallel.For不使用我的主线程
在我的应用程序中,我希望我的主线程不被其他任何东西使用。 我必须做一些并行处理,我希望由不同的线程完成。 为此,我使用Parallel.For如下
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)); }
从输出主线程可以看出使用ThreadID 1和Parallel.For中的一些线程也使用相同的线程。
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
有没有办法确保Parallel.For中的任何内容始终在单独的线程上运行,以便主线程始终是空闲的。
有没有办法确保Parallel.For中的任何内容始终在单独的线程上运行,以便主线程始终是空闲的。
Parallel.For
将一直阻塞直到所有内容都完成 – 所以即使它在原始线程上没有做任何事情,线程仍然不会“自由”。
如果你想保持主线程“免费”你可能想要查看async和await – 你可以使用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
循环中使用,但这没关系,因为它仍然不是你原来的主线程,如果你看到我的意思。