Search code examples
c#processfile-managementunmanagedresources

How to release all resources for a process?


I am running a process, which is creating a file and using that file. After the end of that process, i am deleting that file.

If some exception arises in between then how to know that the file is released by the process or not and how to delete it if it is locked by the process.

Thanks for any help :)


Solution

  • On Windows, when the process ends, the OS returns all resources owned by that process automatically. End of story.

    For example, say you did "CreateFileMapping()" on each of two processes to share a memory segment. When the first process exits, Windows decrements the usage counter, and only the surviving process can still use the object. When the second process does a "CloseHandle()" (or itself exits), the counter is decremented to zero, and the object is completely freed.

    In other words, Windows will reclaim the resource when it's no longer used, whether the processes clean up gracefully after themselves or not.

    And no, even if you open a file for exclusive access, the file itself won't be "locked" once the file handle is closed (and Windows WILL close it automatically when the program terminates).