How to make an async method? (beginner)
-
10 Ağustos 2012 Cuma 13:40
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
Tüm Yanıtlar
-
10 Ağustos 2012 Cuma 15:13
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.
- Yanıt Olarak İşaretleyen Jan Kučera 10 Ağustos 2012 Cuma 15:18