0

I saw that one sealed class is generated for an async/await method. Is it correct that if I have method in a loop like below, Will it create 200 objects for me?

 public async void M() {

    int i=0;
    while(i<100)
    {
        await Method1();            
        await Method2();
        i++;
    }


}

  public async Task Method1() {

      await Task.Delay(10);
  }
 public async Task Method2() {

      await Task.Delay(10);
  }
TRS
  • 1,947
  • 4
  • 26
  • 49
  • You could try running a sealed an non-sealed version of this code with BenchmarkDotNet and check the difference in allocations: https://benchmarkdotnet.org/articles/guides/getting-started.html – Bernard Vander Beken Jan 07 '19 at 09:00
  • This is some what similar to https://stackoverflow.com/questions/28944276/will-every-await-operator-result-in-a-state-machine – dotnetstep Jan 07 '19 at 09:01
  • As far as I understand it, no. You're always `await`ing the return result of the methods, halting code execution until that method is completed. Also your current code will result in a infinite loop, because `i` will always be `0`, place `i+;` inside the while block – MindSwipe Jan 07 '19 at 09:03
  • @MindSwipe thanks for pointing typo,but execution was not the intention in this sample code. – TRS Jan 07 '19 at 09:07
  • 2
    No Problem, it's not a big deal here but as a habit you should always check your code and only post code that compiles. As [Jon Skeet](https://stackoverflow.com/users/22656/jon-skeet) said in his [blog entry](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) about writing the perfect questions "I usually paste it into a text editor, and try to compile it from the command line. If that’s not likely to work I’m unlikely to bother too much with it". Maybe at one point you'll have a larger question and this will help ;) – MindSwipe Jan 07 '19 at 09:11
  • 1
    If you need to see memory usage, use a profiler. By my reading, you'll create 201 objects but at most 2 of them will be reachable at any moment and any others should be collectible *if the GC has to run*. – Damien_The_Unbeliever Jan 07 '19 at 09:12
  • Not 200. Much more. – user4003407 Jan 07 '19 at 09:35
  • @PetSerAl Right. A correct statement is that it will create 200 more than what it would if those methods weren't `async`. You're correct that `Delay` will create at least one new object on each call, and there's an object for the returned task, in addition to the state machine. There are 200 objects (the state machines) that do nothing useful and that could trivially be removed from the code. – Servy Jan 07 '19 at 14:49

0 Answers0