循环中的 C# .NET Core3 XHR 请求

问题描述

我有一个函数可以循环调用 XHR 请求。我想知道是否有其他更有效、更理想的方法来做到这一点。

public async Task<List<StationDevice>> GetMeterReportDevices(string projectId)
{
            List<StationDevice> devices = new List<ReportDevice>();

            Project project = this.projectService.GetProject(projectId);

            // Let's say there are 10000 stations
            List<Station> stations = await this.stationService.GetStations(project.ProjectId);

            foreach (Station station in stations)
            {
                // Let's say there are 1000 station devices
                List<StationDevice> stationDevices = await this.stationService.GetStationDevices(project.ProjectId,station.StationId);
                devices.AddRange(stationDevices);
            }

            return devices;
}

我想知道如何才能更快、更高效地完成这项工作,因为这需要花费大量时间。 如果您想知道,XHR 请求是向第 3 方 API 发出的,因此我们在这方面无能为力。

非常感谢任何帮助。

解决方法

我认为你可以尝试这样的事情:

public async Task<List<StationDevice>> GetMeterReportDevices(string projectId)
{
            List<StationDevice> devices = new List<ReportDevice>();

            Project project = this.projectService.GetProject(projectId);

            // Let's say there are 10000 stations
            List<Station> stations = await this.stationService.GetStations(project.ProjectId);
            var tasks = new List<Task<List<StationDevices>>>();
            foreach (Station station in stations)
            {
               tasks.Add(this.stationService.GetStationDevices(project.ProjectId,station.StationId));
            }

            foreach (var t in tasks)
            {
                // Let's say there are 1000 station devices
                List<StationDevice> stationDevices = await t;
                devices.AddRange(stationDevices);
            }

            return devices;
}

这样你首先触发所有请求,然后开始一个一个等待,其他人处理。