C# USING keyword - when and when not to use it?

后端 未结 3 1452

I\'d like to know when i should and shouldn\'t be wrapping things in a USING block.

From what I understand, the compiler translates it into a try/finally, where the

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 07:44

    To add to the other answers, you should use using (or an explicit Dispose) whenever an object holds any resources other than managed memory. Examples would be things like files, sockets, database connections, or even GDI drawing handles.

    The garbage collector would eventually finalise these objects, but only at some unspecified time in the future. You can't rely on it happening in a timely fashion, and you might have run out of that resource in the meantime.

提交回复
热议问题