Yet another async question: async API

I have been looking for some clarity on this issue for a while now and I can't seem to find what I need. I know that you shouldn't expose a synchronous operation as async using Task.Run when writing an API. It is up to the consumer how it chooses to deal with the blocking call. When you wrap a sync method in a Task.Run, it not truly async, for the method is still blocking. The work has just been offloaded to a different thread. I get that.

My question is, how would I actually write an async method? How would I write an async operation that is not wrapped in a Task.Run or some other background thread? For e.g. I want to write a function called FetchDataAsync(). How would I write this method to make it truly async? All examples in the wild just simulate some sort of I/O operation by using await Task.Delay().

Lets say for e.g WebClient didn't expose a DownloadStringAsync() method, how would I write a DownloadStringAsync() method? What if ExecuteNonQuery() didn't have an ExecuteNonQueryAsync() method, how would I write that without using a Task.Run?

I've been through almost all Stephen Cleary and Toubb's resources and I cannot figure it out. I've been looking at TaskCompletionSource but doesn't seem to do the trick for me. Can anyone help?

by phuck via /r/csharp

Leave a Reply