BKS*_*BKS 3 c# task-parallel-library parallel.foreach
在我的应用程序中,我希望我的主线程不被其他任何东西使用.我必须做一些并行处理,我想通过不同的线程来完成.为此,我使用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));
}
Run Code Online (Sandbox Code Playgroud)
从输出主线程可以看出使用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
Run Code Online (Sandbox Code Playgroud)
有没有办法确保Parallel.For中的任何内容始终在单独的线程上运行,以便主线程始终是空闲的.
有没有办法确保Parallel.For中的任何内容始终在单独的线程上运行,以便主线程始终是空闲的.
Parallel.For将一直阻塞,直到一切都完成 - 所以即使它没有在原始线程上做任何事情,线程仍然不会"免费".
如果你想保持主线程"免费",你可能想要查看异步和等待 - 你可以用Task.Run异步方法启动10个任务,然后await调用结果Task.WhenAll.
或者,您仍然可以使用Parallel.For但在任务中执行此操作.例如:
Task task = Task.Run(() => Parallel.For(0, 10, i =>
{
Console.WriteLine("Output ->>>>>>> {0} ",
Thread.CurrentThread.ManagedThreadId);
}));
Run Code Online (Sandbox Code Playgroud)
然后你可以等待那个任务.任务的"主线程"可能会在Parallel.For循环中使用,但这没关系,因为如果你看到我的意思,它仍然不是你原来的主线程.