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:

  1. starts threadpool thread (task.run),
  2. which start async i/o operation (getasync), , go threadpool.
  3. when i/o done (await), threadpool thread started (configureawait(false)),
  4. which start async i/o operation read content of http response (getasstringasync), , go threadpool.
  5. 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