如何将大 foreach 循环分成批处理并同时处理?

foreach (var deviceId in deviceList)

{

    // register device into IoT hub 

    Device device;

    RegistryManager registryManager = RegistryManager.CreateFromConnectionString("connectionString");

    device = await registryManager.AddDeviceAsync(new Device(deviceId));


    // send message to iot hub

    DeviceClient deviceClient;

    await deviceClient.SendEventAsync("data");                       

}

如果设备是 10000,那么我如何将它分成多个批次并进行处理?


我试过这段代码,但它没有希望


public IEnumerable<user> GetBatch(int pageNumber)

{

    return users.Skip(pageNumber * 1000).Take(1000);

}


莫回无
浏览 186回答 1
1回答

慕田峪7331174

这对于Parallel.ForEach循环来说是一个很好的案例,它将自动将循环处理分布在多个线程中。很容易将您的代码重新安排到这样的循环中,并利用内置的并行库来启用并行处理。这当然假设顺序并不重要(而且它似乎并不基于我们所能看到的一点点)。编辑:如果您确实需要 100 或 200 的特定批次,如评论中所述,您可以使用System.Collections.Concurrent.Partitioner类根据需要打破并行循环,这篇 SO 帖子实际上很好地描述了如何用它。Parallel.ForEach(devices, (device) =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // register device into IoT hub&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Device device;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; RegistryManager registryManager = RegistryManager.CreateFromConnectionString("connectionString");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; device = await registryManager.AddDeviceAsync(new Device(deviceId));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // send message to iot hub&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;DeviceClient deviceClient;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; await deviceClient.SendEventAsync("data");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP