Run multiple instances of same method asynchronously?

前端 未结 6 2052
情深已故
情深已故 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:45

    When using async awaityou're essentially saying "whilst waiting for this task to finish please go off and do some independent work that doesn't rely on this task". As you don't care about waiting for GetDataFor to finish you don't really want to use async await.

    This previous question seems to have a very similar request as yours. With that in mind I think you should be able to do something like this:

    public void SomeMethod()
    {
        Task.Run(() => GetDataFor(i));
    }
    

    Basically, this assumes you don't need to wait for the GetDataFor to finish before doing anything else, it's literally 'fire and forget'.

    With regards to Parallel.For, you are likely to see some improvement in performance so long as you have more than 1 core. If not, you will probably see an ever so slight decrease in performance (more overhead). Here's an article that helps explain how it works.

    UPDATE

    Following your comment then I would suggest something like:

    var TList = new List();
    
    for (var i = 0; i < 100; i++)
    {
        TList.Add(Task.Run(() => GetDataFor(i)));
    }
    
    await Task.WhenAll(TList);     
    

    Here's a useful question that highlights why you might want to use WhenAll instead of WaitAll.

    You might want to include some checking around the status of completion of the tasks to see which failed (if any). See here for an example.

提交回复
热议问题