提高性能异步Parallel.Foreach c#代码 [英] Increase performance async Parallel.Foreach c# code
问题描述
我有一个超过10k项的deviceList,并希望通过调用另一种方法来发送数据。
I have a deviceList of more than 10k items and want to send data by calling another method.
我尝试使用Parallel.Foreach,但我不确定这是否正确。
I tried to use Parallel.Foreach but I'm not sure is this the correct way to do it.
我已经在azure上发布了这个webapp,我有测试这个100它工作正常但是10k它有超时问题。我的实现是否需要任何调整,谢谢
I have published this webapp on azure, I have tested this for 100 it works fine but for 10k it got timeout issue. Is my implementation need any tuning , thanks
private List<Task> taskEventList = new List<Task>();
public async Task ProcessStart()
{
string messageData = "{\"name\":\"DemoData\",\"no\":\"111\"}";
RegistryManager registryManager;
Parallel.ForEach(deviceList, async (device) =>
{
// get details for each device and use key to send message
device = await registryManager.GetDeviceAsync(device.DeviceId);
SendMessages(device.DeviceId, device.Key, messageData);
});
if (taskEventList.Count > 0)
{
await Task.WhenAll(taskEventList);
}
}
private void SendMessages(string deviceId, string Key, string messageData)
{
DeviceClient deviceClient = DeviceClient.Create(hostName, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), Microsoft.Azure.Devices.Client.TransportType.Mqtt);
//created separate Task
var taskEvents = Task.Run(() => ProcessMessages(deviceId, string messageData));
taskEventList.Add(taskEvents);
}
private async Task ProcessMessages(string deviceId, string messageData)
{
var startTime = DateTime.UtcNow;
while (DateTime.UtcNow - startTime < TimeSpan.FromMinutes(15))
{
await deviceClient.SendEventAsync(messageData);
}
}
推荐答案
您好Ashuthinks32,
Hi Ashuthinks32,
看起来您收到了您发布的问题
上的解决方案Stack Overflow。如果该解决方案适合您,请告诉我们。
It looks like you have received a solution on the question you posted on Stack Overflow. Please let us know if that solution worked for you.
这篇关于提高性能异步Parallel.Foreach c#代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!