c# - async await for concurrency on long function -
i'm trying process many tasks concurrently don't require eachothers completion move onto next task. used synchronous process , tried turn asynchronous. when measuring performance both methods take same time finish (around 30 seconds), i'd expect async faster... if i've 1) got below right 2) understand async beneficial (i suspect 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 programme = 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(); }
}
async
doesn't run code on thread pool. if want execute cpu-bound code on different threads, need utilize task.run
:
task processasync(int seed){ var task = new expensivetask(seed); homecoming task.run(() => task.process()); }
c# async-await c#-5.0
No comments:
Post a Comment