0

If i have a method that invokes another method in this style:

private void MyMethod()
{
    // get a command object in a queue to process.
    var currentObject = this.Queue.Pop();

    // now call itself recursively for next command object in queue...
    Task.Run(async () => {

      // begin awaited async execution of the command object...
      // end of execution

      // do a recursive call once awaited async operation above is done
      this.MyMethod();

    });
}

I basically have a queue of objects that i need to execute in an asynchronous fashion. Where each consecutive object is not executed until the previous one completes.

Do these recursive calls of async tasks have performance implications and/or negative side effects?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
AlvinfromDiaspar
  • 6,611
  • 13
  • 75
  • 140
  • 1
    Why are you using `async` here, when `MyMethod` is synchronous? – Pavel Anikhouski Apr 24 '20 at 16:47
  • good point. i will update the snippet to reflect what i have more closely. – AlvinfromDiaspar Apr 24 '20 at 16:51
  • 2
    I'll answer without taking into consideration that your 'MyMehod' is sync as @PavelAnikhouski said. As a thumb rule don't use recursion since it is not stack-friendly and just use loops. I don't know what the implications of using recursion on async scenario but prefer not to test it. – DeJaVo Apr 24 '20 at 16:51
  • 2
    You may find your answer here - https://stackoverflow.com/questions/25007709/what-is-the-correct-way-to-use-async-await-in-a-recursive-method which may point to a possible duplication – DeJaVo Apr 24 '20 at 16:52
  • Thanks @DeJaVo. I thought about using a loop, but i couldnt think of a way to utilize a loop while keeping the execution of my commands asynchronous. Because i would like the UI to still be responsive during the execution of the entire queue. – AlvinfromDiaspar Apr 24 '20 at 16:55
  • You can use Dispatcher Invoke method while using a loop.https://learn.microsoft.com/en-us/dotnet/api/system.windows.threading.dispatcher.invoke?view=netframework-4.8 – DeJaVo Apr 24 '20 at 16:57
  • I use the dispatcher all the time to ensure UI related updates are done on the main thread. But how would the dispatcher help address this question regarding async operations in loops? – AlvinfromDiaspar Apr 24 '20 at 16:59
  • 1
    "a way to utilize a loop while keeping the execution of my commands asynchronous" You put each task--without awaiting it--in an array; then `await Task.WhenAll` the array. – Kenneth K. Apr 24 '20 at 17:01
  • The `Task.Run` is not awaited, so it creates fired-and-forgotten tasks. How are you going to handle possible exceptions this way? – Theodor Zoulias Apr 24 '20 at 19:51

0 Answers0