Async task inside parallel.for loop

I have an async method called from the code Parallel.Forbelow. Now, looking at the code, it is pretty straightforward, except that the JsonParse class has a static method that does all this - it calls the web service to load the json string and convert it to a PairResults object and return.

The problem that I encountered is that the cycle Parallel.Fornever ends, I clearly see that the data comes from the "item.part1 = data.value" webcam, everything works fine, but updateAllResults never ends. What am I doing wrong?

public void updateAllResults()
{ 
    Parallel.For(0, PairList.Count(), (i) =>
    {            
         var item = PairList[i];
         var data = (Parse.JsonParse<PairResults>
                             .getJsonString("http://localhost:22354/" 
                                                        + item.Original)).Result;
         item.part1 = data.value;
    }); 
}
+2
source share
2

-patern Parallel.For, . , , parallelism , :

public void updateAllResults()
{
    var tasks = PairList.Select(async (item) => 
    {
        var data = await Parse.JsonParse<PairResults>
            .getJsonString("http://localhost:22354/" + item.Original).
            .ConfigureAwait(false);

        item.part1 = data.value;
    });

    Task.WaitAll(tasks.ToArray());
}

, . Parallel.For, , WinForms. Task.WhenAll:

public async Task updateAllResults()
{
    var tasks = PairList.Select(async (item) => 
    {
        var data = await Parse.JsonParse<PairResults>
            .getJsonString("http://localhost:22354/" + item.Original)
            .ConfigureAwait(false);

        item.part1 = data.value;
    });

    await Task.WhenAll(tasks.ToArray());
}

// button click handler
async void button_Click(object s, EventArgs e)
{
    this.button.Enabled = false;
    try
    {
        await updateAllResults()
    }
    finally
    {
        this.button.Enabled = true;
    }
}
+5

. , , , for. , . Parallel.For , , .

+2

Source: https://habr.com/ru/post/1533147/


All Articles