0

I'm working on an API that enables C# to communicate and manage GNS projects easily. Now I'm looking for an efficient way to run and stop the projects. You can do it pretty much easily by simple POST requests synchronously. However, this process take some time so I'm trying to make it asynchronous since PostAsync let you do if I'm not mistaken.

Sadly, when I try to run my code, this breaks so bad. This is part where all the problem comes up:

// Change the status of the project (start or stop)
private void ChangeProjectStatus(string status){

    // First part of the URL
    string URLHeader = $"http://{host}:{port}/v2/projects/{projectID}/nodes";

    // Number of nodes
    int numNodes = nodes.Length;

    // Pack the content we will send
    string content = JsonConvert.SerializeObject(new Dictionary<string, string> { { "-d", "{}" } });
    ByteArrayContent byteContent = new ByteArrayContent(System.Text.Encoding.UTF8.GetBytes(content));
    byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

    if (status.Equals("start"))
        Console.WriteLine("Activating all the nodes in the project...");
    else
        Console.WriteLine("Deactivating all the nodes in the project...");
    Task<System.Net.Http.HttpResponseMessage>[] tasks = new Task<System.Net.Http.HttpResponseMessage>[nodes.Length];
    for (ushort i = 0; i < nodes.Length; i++){
        try{
            tasks[i] = HTTPclient.PostAsync($"{URLHeader}/{nodes[i].ID}/{status}", byteContent);
        } catch(Exception err){
            Console.Error.WriteLine("Impossible to {2} node {0}: {1}", nodes[i].Name, err.Message, status);
        }
    }
    Task.WaitAll(tasks);
    Console.WriteLine("...ok");
}

The error I get (from the WaitAll() block actually) is:

An item with the same key has already been added. Key: Content-Length

Any idea on how to fix it?

aorestr
  • 21
  • 2
  • Please read this (https://github.com/google/google-api-dotnet-client/issues/548) – Ryan Wilson Jun 18 '18 at 19:09
  • I think what you're looking for is `await Task.WhenAll(...)` which is the recommended method to wait for multiple async operations to complete. https://stackoverflow.com/questions/6123406/waitall-vs-whenall – WolfgangDeveloper Jun 18 '18 at 19:32

0 Answers0