My requirement is quite weird.
I have SomeMethod()
which calls GetDataFor()
.
public void SomeMethod()
{
for(int i = 0; i<100; i++) {
var data = GetDataFor(i);
}
}
public data GetDataFor(int i) {
//call a remote API
//to generate data for i
//store to database
return data;
}
For each i
, the end result will always be different. There is no need to wait for GetDataFor(i)
to complete before calling GetDataFor(i+1)
.
In other words I need to:
- call
GetDataFor()
for eachi+1
immediately after successfully callingi
(Calling them in parallel looks impossible) - wait until all the 100 instances of
GetDataFor()
are completed running - leave the scope of
SomeMethod()
Following YK1's answer, I have tried to modify it like this:
public async Task<void> SomeMethod()
{
for(int i = 0; i < 100; i++) {
var task = Task.Run(() => GetDataFor(i));
var data = await task;
}
}
It didn't thrown any errors but I need to understand the concept behind this:
- How
task
will distinguish between different calls forawait
ing? It is getting over-written. - Is it blatantly wrong way to do this? So, how do do it right?