问题
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