I’m trying to process many tasks concurrently as they don’t require eachothers completion to move onto the next Task. I used the synchronous process and tried to turn it asynchronous. However when measuring performance both methods take exactly the same time to complete (around 30 seconds), i’d expect the Async to be faster… if i’ve 1) got the below correct 2) understand what async is beneficial for (i suspect this is the issue).
public class ExpensiveTask {
private int _seed;
public ExpensiveTask(int seed){ _seed = seed; }
public Process() { //TODO various things }
}
public class Controller {
public static void main(string[] args){
var program = new Controller();
program.RunAsync(); // Runtime 36.9s
program.Run(); // Runtime 36.6s
}
void Run(){
Process(1);
Process(2);
Process(3);
}
async void RunAsync(){
var taskList = new List<Task>();
taskList.Add(ProcessAsync(1));
taskList.Add(ProcessAsync(2));
taskList.Add(ProcessAsync(3));
await Task.WhenAll(taskList);
}
async Task ProcessAsync(int seed){
var task = new ExpensiveTask(seed);
task.Process();
}
void Process(int seed){
var task = new ExpensiveTask(seed);
task.Process();
}
}
asyncdoesn’t run your code on the thread pool. If you want to execute your CPU-bound code on different threads, you need to useTask.Run: