JKP
JKP

Reputation: 9

.NET - What happens to tasks that don't complete before the method finishes?

Apologies if this isn't asked well--this basically my first time posting, but I'm a long time lurker.

I'm troubleshooting some .NET6 code that is looping through a list of a few thousand items, and the code is essentially this:

public async Task MyMethod()
{
    foreach (var thing in things)
    {
        _ = Task.Run(async () => DoSomeStuffThatTakesAWhile(thing))
    }
}

The DoSomeStuffThatTakesAWhile() has a log at the very top, so I can see when each task gets into there. What I'm seeing is those logs for about 20% of the items in the list, and then nothing else. No errors, exceptions, or any other indications of a problem. It seems to abruptly just stop part way down the list.

I'm not able to make code changes at the moment and think I could answer this question myself with a little bit of logging. But unfortunately that's not an option at the moment.

I expected to see the log from DoSomeStuffThatTakesAWhile() for each of the items in the list.

My theory is that any tasks that were not scheduled onto a thread by the time MyMethod() completes are just getting dropped and never run. Is that how this works? I'm thinking that sticking those tasks into a list and doing a WaitAll() at the end of MyMethod might resolve this.

Any help or thoughts would be appreciated.

Upvotes: 0

Views: 93

Answers (0)

Related Questions