提高性能异步Parallel.Foreach

时间:2019-03-15 17:00:04

标签: c# multithreading performance task-parallel-library

我的deviceList超过1万个项目,并且希望通过调用其他方法来发送数据。

我尝试使用Parallel.Foreach,但是我不确定这是否是正确的方法。

我已经在azure上发布了此webapp,我对此进行了100次测试,效果很好,但10k时出现超时问题。我的实现是否需要任何调整,谢谢

savedInstanceState

1 个答案:

答案 0 :(得分:4)

至少肯定有比赛条件。 Parallel 仅用于同步代码,而不是异步代码。

据我所知,您不需要ParallelTask.Run(它们都是ASP.NET服务的反模式):

public async Task ProcessStart()
{
  string messageData = "{\"name\":\"DemoData\",\"no\":\"111\"}";
  RegistryManager registryManager;

  var tasks = deviceList.Select(async device =>
  {
    // get details for each device and use key to send message
    device = await registryManager.GetDeviceAsync(device.DeviceId);
    await SendMessagesAsync(device.DeviceId, device.Key, messageData);
  }).ToList();

  await Task.WhenAll(tasks);
}

private async Task SendMessagesAsync(string deviceId, string Key, string messageData)
{
  DeviceClient deviceClient = DeviceClient.Create(hostName, new DeviceAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey), Microsoft.Azure.Devices.Client.TransportType.Mqtt);
  await ProcessMessagesAsync(deviceId, string messageData);
}

private async Task ProcessMessagesAsync(string deviceId, string messageData)
{
  var startTime = DateTime.UtcNow;
  while (DateTime.UtcNow - startTime < TimeSpan.FromMinutes(15))
  {
    await deviceClient.SendEventAsync(messageData);
  }
}
  

10k出现超时问题。

15分钟是HTTP请求的时间。我认为应该退后一步,看看是否有更好的方法来构建整个系统。

相关问题