问题
I have gotten it through my head (perhaps incorrectly) that library methods that take some time should generally be made async. Is that true, and if so, how should that be done when there is nothing to await within the library method? I am designing my own library with the method:
public Dictionary<FunctionEnum, double> Evaluate(Func<uint,uint> algorithm, IList<double>
suggestedList)
It takes in a method that takes a uint and returns a uint and uses that method many times over. In brief, I'm evaluating the complexity (BigO) of an algorithm by least squares. For the gory details see:
https://codereview.stackexchange.com/questions/236557/my-c-code-to-evaluate-order-of-algorithm-is-returning-logn-or-n3-instead-of-n?noredirect=1#comment463662_236557
and if my question is better suited for codereview.stackexchange, please tell me.
The method Evaluate takes quite some time because it must call the algorithm method that is passed in many times. The algorithm method is not async.
I could certainly put the entire loop where algorithm is called inside a Task and await the Task but various articles suggested this is a poor idea (Example: https://channel9.msdn.com/Events/TechEd/Europe/2013/DEV-B318)
In this particular exercise, I have control of some (but not all) of the code that defines algorithms, so the algorithm method could well be defined as:
async Task<uint> algorithm(uint) { // perform algorithm }
and I'm guessing my signature would become:
public async Task<Dictionary<FunctionEnum, double>> Evaluate(Func<uint,Task<uint>> algorithm, IList<double>
suggestedList)
In this case, I can certainly make Evaluate async and can certainly call
await algorithm((uint) trial[i]);
but in general, it's not unreasonable that somebody would want to call my Evaluate method with a non-async method, and I'd like to provide him/her with an estimate that their algorithm is O(N), O(NLogN), etc.
Also, it's not clear (to me) that I could make the algorithm method truly async without introducing a Task in the body of the algorithm method. Consider for example
uint Fib(uint n) { return the nth Fibonnacci element).
This method could take a long time (for large n), but again, how would one make it an async method? Introduce something like await Task.Factory.StartNew( () => FibbonaciImplmentation(n); ); ??
Ideas? Thanks!
来源:https://stackoverflow.com/questions/60047175/library-method-async-or-not