Does the task still survive when the main thread that creates it has been killed in c#?

随声附和 提交于 2021-02-07 11:10:37

问题


I have a main thread that creates a task using:

new TaskFactory(cancellationToken).StartNew(() => DoSomething(cancellationToken), 
                                            TaskCreationOptions.LongRunning);

I wonder if the task still survive when the main thread that creates the task has been killed in c#.


回答1:


If a process' main thread is terminated, the process aborts. When a process is killed, all threads (and other owned resources) are closed/terminated/killed also.

Therefore, if your process' main thread created a worker thread and the main thread is killed, the worker thread is also terminated.

Don't be confused by the TaskCreationOptions.LongRunning enum - this is just an indicator to the underlying thread-pool manager that it might want to create this thread outside the normal constraints on maximum thread-pool size.




回答2:


If AppDomain (usually equal to process) survives "killing" of the thread that created the task then task will continue to exist.

What happens when task try to finish depends on synchronization context - if it had to continue on aborted thread it will throw/hang, if it can continue on thread pool thread than task will be able to finish.

Note that usually for UI based apps aborting main thread means at least stopping event loop which will result in process to be considered "unresponsive" and possibly killed.



来源:https://stackoverflow.com/questions/32261314/does-the-task-still-survive-when-the-main-thread-that-creates-it-has-been-killed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!