如何从List.ForEach C#进行异步调用

我有项目列表和我想要调用UploadChunkToServer方法的每个项目,但是并行.列表中始终只有4个项目.

if (DataQueue.Count == NumberofChunksToRead)
{
    DataQueue.ToList().ForEach(Chunk =>
    {
        UploadChunkToServer(Chunk);
    });
}

以上是我在方法中的代码调用,方法签名如下.

private void UploadChunkToServer(UserCustomFile Chunk)
{
    var client = new RestClient(Helper.GetServerURL());

    var request = new RestRequest("api/fileupload/savechunk", Method.POST);
    request.AddHeader("Content-type", "application/json");
    request.RequestFormat = RestSharp.DataFormat.Json;
    request.AddJsonBody(Chunk);

    client.ExecuteAsync(request, response =>
    {
        if (response.StatusCode != System.Net.HttpStatusCode.OK)
        {
            throw new Exception(response.ErrorMessage);
        }
        else
        {
            ChunkStatuses.Add(Chunk.ChunkID);
        }
    });
}

我试图添加异步运算符,但没有运气.有什么想法可以实现吗?

最佳答案 也许你可以具体使用
Parallel和ForEach:

Parallel.ForEach(DataQueue.ToList(), Chunk =>
                 {
                      UploadChunkToServer(Chunk);
                 });
点赞