Suppose you use a ThreadPool
to perform some operations and assume that each operation writes on a file. All threads of ThreadPool
are background threads, so they will be terminated when closing the application. What happens if the application is closed while a thread of ThreadPool
is writing a file to disk?
Operating system will close the file handle as the part of terminating the process.
- Any pending asynchronous I/O will be canceled
- Any data in the write buffer which isn't flushed gets lost
Read the MSDN article on Foreground and Background threads
ThreadPool threads are background threads. From the article:
When the runtime stops a background thread because the process is shutting down, no exception is thrown in the thread.
The thread simply stops. It executes one instruction, and never executes the next. The FileStream will be closed as part of the CLR clearing up.
FileStream
go unreachable when ThreadPool
threading is writing with it? –
Matson You can easily try this situation by calling Environment.Exit(0)
and Environment.Exit(1)
method (successfull exit and exit with error). I think that all the handles for the file will be removed, and the only data already written to the disk will remain, without flushing the buffers.
Althrough, the file could became unaccessible with some strange error like The file is being used by another process
or something in case of error exiting the process.
.Exit()
doesn't matter; in both cases the application terminates gracefully (meaning finally
-blocks and finalizers will run). While you're experimenting, try Environment.FailFast()
, as that, unlike Exit()
, is not a graceful termination and will bypass finalizers. Note that flushing buffers is something that could be done in a finalizer, but the BCL classes typically don't (which is a shame, since the OS closes handles anyway and that's the only added value the finalizer would have). –
Efthim © 2022 - 2024 — McMap. All rights reserved.