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

前端 未结 2 1049
眼角桃花
眼角桃花 2020-12-11 20:55

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:

2条回答
  •  醉话见心
    2020-12-11 20:59

    By definition, after program terminates, no code can run. This has nothing to do with Task.Run().

    If what you're actually asking is something like:

    Tasks run on background threads, so if the main thread completes (e.g. after the user closes the main window), they are not guaranteed to run to completion or even start, how can I fix that?

    Then there are two options: either don't let the main thread complete (e.g. by calling Task.WaitAll() as Jon Skeet suggests), or run your important Tasks on a foreground thread. To do that, you can use QueuedTaskScheduler from ParallelExtensionsExtras.

提交回复
热议问题