c# - Unmanaged resources and Dispose() -


i reading articles dispose() method , found unmanaged resources should freed explicitly dispose() method (or finalize() method) , article says file handles , database connection objects examples of unmanaged resources. can explain why unmanaged , happens if not handled in dispose()? have no idea file handle is. exist?

in context it's perhaps easiest think of this:

  • an unmanaged resource resource obtained making windows api call returns windows handle must freed @ point.

  • the other kind of resource memory. managed automatically if allocated .net. (note there ways allocate memory using windows api; counts unmanaged resource.)

for example, filestream class calls windows api open file, filestream keeps file handle internally. file handle represents unmanaged resource must freed @ point.

filestream uses windows api function createfile() behind scenes. handle returned createfile represents unmanaged resource.

if don't free handles, remain allocated duration of program, .net classes have unmanaged resource provide finalizer (see below) make sure will freed @ point.

(but if writing own file handling class , forgot free file handle anywhere @ all, file remain open until program exited.)

normally such unmanaged resources freed in two places:

  • the dispose() method. should normal way dispose unmanaged resources.

  • the finalizer. last-resort mechanism. if class has finalizer called garbage collector when cleans dead object. class has unmanaged resource should have finalizer clean if programmer forgets call dispose().

this of simplification, understand hope.

for full details, see this msdn article on dispose pattern.


Comments

Popular posts from this blog

.htaccess - First slash is removed after domain when entering a webpage in the browser -

Automatically create pages in phpfox -

c# - Farseer ContactListener is not working -