在任务限制下按顺序运行一组任务
假设您有一个场景需要执行大量任务(例如,100),但您想要限制同时运行的任务数量(例如 10)。使用 .NET Framework 4.0 中引入的“Task”类可以有效解决这个问题。
在给定的场景中,我们可以利用“SemaphoreSlim”类来控制同时运行的最大任务数。 “SemaphoreSlim”允许您创建一个可以限制并发操作数量的信号量对象。
这是一个示例实现,演示如何实现您想要的行为:
using System.Threading.Tasks; using System.Threading; class Program { static void Main() { // Create a SemaphoreSlim object to limit the number of concurrent tasks to 10 SemaphoreSlim maxThread = new SemaphoreSlim(10); // Create 115 tasks with each task performing a specific action for (int i = 0; i < 115; i++) { // Acquire a permit from the SemaphoreSlim object, blocking if the limit is reached maxThread.Wait(); // Schedule a new task Task.Factory.StartNew(() => { // Perform your desired task here }, TaskCreationOptions.LongRunning) // Once the task is complete, release the permit back to the SemaphoreSlim object .ContinueWith((task) => maxThread.Release()); } } }
在此实现中,每个任务在执行之前都会从“SemaphoreSlim”对象获取许可。如果已获取最大数量的许可证(本例中为 10 个),则信号量会阻止后续任务获取许可证,直到释放许可证为止。
通过使用此方法,您可以顺序执行一组任务,确保只有预定义数量的任务同时运行。一旦所有任务完成,“Main”方法就会退出,表示程序结束。
以上是如何在 .NET 中以有限数量的并发任务顺序运行多个任务?的详细内容。更多信息请关注PHP中文网其他相关文章!