Locked How to make an async method? (beginner)

  • Friday, August 10, 2012 1:40 PM
     
     

    Hello,

    it seems that all tutorials I have seen on async so far shows you how to use another async methods to get your stuff done asynchronously. What I am not sure I get is how do you make your async method that does not call anything else? Any tutorial for writing async aware libraries?

    Data processing is one of such examples, say I want to write an method which takes huge array of numbers and transforms them somehow, supposedly taking a long time to finish. So how should this be written? Should I do not care at all, write it like synchronously and let the caller somehow get it? Any guidelines or similar?

    Thanks for hints or links!
    Jan

All Replies

  • Friday, August 10, 2012 3:13 PM
     
     Answered

    Well, the whole point of the new async functionality is that it allows you to combine existing async functionality, it's not for writing the most low-level async functions.

    In your specific case of long-running CPU-bound method, I probably wouldn't make it async and would let the user decide whether he wants to use it synchronously or whether he wants to specifically run it on a background thread. But it's certainly an option to make it async. The way you would do that (either in the library or as a user who decided he wants to use it asynchronously) is to use Task.Run() (basically shorthand for the old Task.Factory.StartNew()).

    If you want to implement some other low-level async operation (so you can't use await or Task.Run()), you can do that using TaskCompletionSource. Your method would somehow start the operation and return the source's Task. Then, when the operation finishes, it would set the result of the Task through the source.

    • Marked As Answer by Jan Kučera Friday, August 10, 2012 3:18 PM
    •