Run multiple instances of same method asynchronously?

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

    Although your original code is overwriting the values, it seems like you are trying to combine the results of parallel operations. If so, consider using Task.ContinueWith to process the return values. Your code would look something like this:

    public void SomeMethod()
        List tasks = new List();
        for (var i = 0; i < 100; i++)
        {
            tasks.Add(Task.Run(() => GetDataFor(i)).ContinueWith((antecedent) => {
                // Process the results here.
            }));
        }
        Task.WaitAll(tasks.ToArray());
    }
    

提交回复
热议问题