I would like to know how is the best way to implement my own async method. I have read this article and it says that is not a good idea to wrapper a sync method into a task and use it as async method, because this way use other thread and use more resources, that is what we want to avoid with use async.
In the article use TaskCompletionSource, but I don’t know exactly how to use it. Which is the purpose of TaskCompletionSource?
The best resource for writing
asyncmethod is the Task-based Asynchronous Pattern (TAP) document by Stephen Toub. Much of the information in that document is now part of the official MSDN documentation.If you want a shorter (but still thorough) tutorial, I recommend my own
async/awaitintro blog post, and there are several other tutorials out there. Once you have learned a bit aboutasync, the next good resource is the officialasync/awaitFAQ.There are also tons of great
asyncvideos on Channel9. Many (most?) of them discussasyncwhen it was still a CTP, but very few design changes were made when it went into production.To answer your specific question,
TaskCompletionSourceis used to create aTaskwrapper around an existing asynchronous operation (e.g., an I/O operation, timer, or event). You can’t execute code in aTaskcreated byTaskCompletionSource; you should useTask.Runto execute code in aTask.