Run multiple instances of same method asynchronously?

前端 未结 6 2026
情深已故
情深已故 2021-01-03 09:32

My requirement is quite weird.

I have SomeMethod() which calls GetDataFor().

public void SomeMethod()
{
    for(int i = 0         


        
6条回答
  •  迷失自我
    2021-01-03 10:00

    The code actually makes no sense.

    How task will distinguish between different calls for awaiting? It is getting over-written.

    It does not get overwritten. Because...

    for(int i = 0; i < 100; i++) {
        var task = Task.Run(() => GetDataFor(i));
        var data = await task;
    }
    

    This is WAITING for every request to finish before continuing the loop. Await waits for the end.

    Which means the whole task thing is irrelevant - nothing happens in parallel here. You can cut some minor overhead by doing it without a task.

    I suspect the OP wanted to achieve something that he simply did not and he was not spending enough time debugging to realize he has single threaded the whole loop again.

提交回复
热议问题