Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nested and child tasks wrong output #36

Closed
exzzy22 opened this issue Jan 30, 2022 · 3 comments
Closed

Nested and child tasks wrong output #36

exzzy22 opened this issue Jan 30, 2022 · 3 comments

Comments

@exzzy22
Copy link

exzzy22 commented Jan 30, 2022

On page 522 the whole code looks like this

using static System.Console;

Task outerTask = Task.Factory.StartNew(OuterMethod);
outerTask.Wait();
WriteLine("Console app is stopping.");

static void OuterMethod()
{
    WriteLine("Outer method starting...");
    Task innerTask = Task.Factory.StartNew(InnerMethod);
    WriteLine("Outer method finished.");
}
static void InnerMethod()
{
    WriteLine("Inner method starting...");
    Thread.Sleep(2000);
    WriteLine("Inner method finished.");
}

But the output i get is always

Outer method starting...
Outer method finished.
Console app is stopping.

Inner method never gets called for some reason. Also later when you do attach to parent i get this

Outer method starting...
Outer method finished.
Inner method starting...
Inner method finished.
Console app is stopping.

Outer method always starts and finish before inner method starts.

@markjprice
Copy link
Owner

At the bottom of page 522 I say, "Note that, although we wait for the outer task to finish, its inner task does not have to finish as well. In fact, the outer task might finish, and the console app could end, before the inner task even starts!"

This is the behavior that you are seeing. Continue to step 6 to force the inner method to run by adding the parameter that makes it a child task:
https://github.com/markjprice/cs10dotnet6/blob/main/vs4win/Chapter12/NestedAndChildTasks/Program.cs#L11

@exzzy22
Copy link
Author

exzzy22 commented Jan 31, 2022

Sorry i missed that somehow, have a really hard time understanding this section.

@markjprice
Copy link
Owner

The performance chapter is one of the trickiest to learn so do not be too concerned. It is the sort of thing that you can come back to if you ever need to implement it in a real project.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants