Method returns an IDisposable - Should I dispose of the result, even if it's not assigned to anything?

前端 未结 4 1965
轻奢々
轻奢々 2021-01-13 05:08

This seems like a fairly straightforward question, but I couldn\'t find this particular use-case after some searching around.

Suppose I have a simple method that,

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-13 06:08

    Yes, you don't want to leave the FileStream opened. For one, you won't even be able to open the file yourself after that. Calling Close() is good enough, but using using is probably the preferred pattern.

    There's a much bigger problem with your code however. It cannot possibly work reliably on Windows. A typical scenario:

    • The File.Open() call succeeds. You close it
    • Your thread gets pre-empted by the Windows scheduler
    • Another thread in another process gets a chance to run, it opens the file
    • Your thread regains the CPU and continues after the File.Open() call
    • You open the file, trusting that it will work since IsOpen() returned false.

    Kaboom.

    Never write code like this, failure is extremely hard to diagnose. Only ever open a file when you are ready to start reading or writing to it. And don't close it until you are done.

    Extra bonus: it is now obvious that you want to use a using statement.

提交回复
热议问题