Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

.net - What happens to work scheduled by Task.Run() after the program terminates?

I was doing some tests with the TPL and async/await and noticed something that I find unexpected: I was scheduling work to run using lambdas and Task.Run, for instance:

Task.Run(()=>Console.WriteLine("Nice program"));

And then I realized that if program immediately returns the work is never executed. Is that the expected behavior in any .NET application (WPF, Forms, etc.)? Is there any documentation that discusses this?

This means that Task.Run is actually a no-go for fire-and-forget scenarios.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This means that Task.Run is actually a no-go for fire-and-forget scenarios.

Well, you don't want to forget - you want to wait until it's completed. So use the Task that's returned to you.

To do that, you'll need to keep track of all uncompleted tasks that you launch this way, and then use something like Task.WaitAll(tasks) in a non-background thread. You potentially don't need to remember the tasks themselves - you just need to have a counter which is decremented when each task completes, and then you just need to wait for that to get to zero.

It's hard to give more concrete advice than that without knowing more about your scenario, to be honest... but something like that would certainly work.

You can easily encapsulate this in your own convenience methods, of course.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...