I know that you should use async only for materials that are not "CPU intensive", for example. file recordings, web calls, etc., so I also know that it makes no sense to wrap each method in Task.Run or something like that.
However, what should I do when I know that the method makes a web call, but it does not offer an asynchronous interface. In this case, is it worth wrapping it?
Specific example:
I am using CSOM (the SharePoint client object model) in my WebApi application (server) and want to get a list of SharePoint.
This is usually done as follows:
[HttpGet] [Route("foo/{webUrl}")] public int GetNumberOfLists(string webUrl) { using (ClientContext context = new ClientContext(webUrl)) { Web web = context.Web; context.Load(web.Lists); context.ExecuteQuery(); return web.Lists.Count; } }
And I thought about changing it to something like this:
[HttpGet] [Route("foo/{webUrl}")] public async Task<int> GetNumberOfLists(string webUrl) { using (ClientContext context = new ClientContext(webUrl)) { Web web = context.Web; context.Load(web.Lists); await Task.Run(() => clientContext.ExecuteQuery()); return web.Lists.Count; } }
Does it make sense and does it help? As far as I understand, I just create / need a new thread to execute the request ("overhead"), but at least the request stream will be free / ready for another request (that would be good).
But is it worth it, and should it be done so?
If yes: Is it not strange that Microsoft does not offer an “asynchronous” method out of the box, or do they just not care about it?
edit: updated to use Task.Run as indicated in the comment.