c# - Correct way to make async method -
is following correct way make async method, code in method have multiple async calls needs waited on. plan start multiple of method, , when wait of them finish before code continues.
public static task<string> get(string url) { return task.run(async () => { var client = getbasehttpclient(); var result = await client.getasync(url).configureawait(false); if (result.issuccessstatuscode) { return await result.content.readasstringasync(); } return null; }); }
your code:
- starts threadpool thread (
task.run), - which start async i/o operation (
getasync), , go threadpool. - when i/o done (
await), threadpool thread started (configureawait(false)), - which start async i/o operation read content of http response (
getasstringasync), , go threadpool. - when i/o done (
await), threadpool thread started return content calling method.
you skip step 1. altogether. defer call getbasehttpclient threadpool thread, i'll assume not intensive cpu-bound work - in case, could/should done synchronously.
public static async task<string> get(string url) { var client = getbasehttpclient(); var result = await client.getasync(url).configureawait(false); if (result.issuccessstatuscode) { return await result.content.readasstringasync(); } return null; } calling code be:
var tasks = urls.select(get); var responses = await task.whenall(tasks);
Comments
Post a Comment