我正在尝试同时处理许多任务,因为它们不需要彼此完成即可进入下一个任务。我使用了同步过程并尝试将其变为异步。但是,在测量性能时,这两种方法都需要完全相同的时间(大约 30 秒),我希望 Async 更快......如果我有 1)得到以下正确 2)了解什么 async 是有益的(我怀疑这是问题)。
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();
}
}