Run multiple instances of same method asynchronously?

前端 未结 6 2069
情深已故
情深已故 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 09:44

    There's a couple of different approaches.

    First, you could keep it synchronous and just execute them in parallel (on different threads). Parallel LINQ is better than Parallel if you want to collect all the results in the calling method before continuing:

    public data[] SomeMethod()
    {
      return Enumerable.Range(0, 100)
          .AsParallel().AsOrdered()
          .Select(GetDataFor).ToArray();
    }
    

    Second, you could make it asynchronous. To make something truly asynchronous, you need to start at the lowest level (in this case, "call a remote API" and "store to database") and make that asynchronous first. Then you can make GetDataFor asynchronous:

    public async Task GetDataForAsync(int i)
    {
      await .. //call a remote API asynchronously
      await .. //store to database asynchronously
      return data;
    }
    

    Then you can make SomeMethod asynchronous as well:

    public Task SomeMethodAsync()
    {
      return Task.WhenAll(
          Enumerable.Range(0, 100).Select(GetDataForAsync)
      );
    }
    

    Making the code asynchronous is more work - more of the code has to change - but it's better in terms of scalability and resource use.

提交回复
热议问题