RingDotNetfor Ring

Releasing resources

A file you opened stays locked until you give it back. This lesson shows what a leaked resource does, how Dispose gives it back, and how to be sure that the clean-up runs even when an error happens.

What you will learn#

Resources#

Memory is cleaned automatically, but some things are lent by the operating system: open files, network connections, database connections, window handles. While you hold one, others may be unable to use it — a file that is open for writing cannot be deleted or moved, a connection counts against the limit of the server. You must give them back. In .NET the method is Dispose() (many classes also have Close(), which does the same).

The program#

samples/UsingDotNet/tutorials/ch06_dispose.ring
# releasing resources - files that stay locked, Dispose, and cleaning up even when an error happens
load "dotnet.ring"

using {
	"System"
	"System.IO"
}

func main

	cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet_dispose.txt"])
	new File().WriteAllText([ :path = cFile, :contents = "some text" ])

	# 1. A resource is something the operating system lends to your program: a file, a socket, a database connection.
	#    While you hold it, others may not be able to use it. Open the file for writing and try to delete it.
	oStream = new File().Open([ :path = cFile, :mode = "Open" ])
	? "1. the file is open. Can we delete it now? " + yesNo(tryDelete(cFile))

	# 2. Dispose gives the resource back. After it the delete works.
	oStream.Dispose()
	? nl + "2. after Dispose. Can we delete it now? " + yesNo(tryDelete(cFile))

	# 3. If an error happens between opening and closing, a Dispose at the end of the code is skipped. Look at this function:
	new File().WriteAllText([ :path = cFile, :contents = "line 1" + windowsnl() + "line 2" ])
	? nl + "3. a reader without a clean-up, and an error while reading:"
	oLeaked = readBadly(cFile)
	? "   the file is still locked after the error: " + yesNo(not tryDelete(cFile))
	? "   (Ring forgot the variable when the function ended, but the .NET reader is still open)"
	oLeaked.Dispose()                           # for the tutorial: clean up our own mess

	# 4. The same with try / catch / done: the clean-up goes where it is always reached
	new File().WriteAllText([ :path = cFile, :contents = "line 1" + windowsnl() + "line 2" ])
	? nl + "4. the careful way:"
	readCarefully(cFile)
	? "   the file can be deleted after the error: " + yesNo(tryDelete(cFile))

	new File().Delete(cFile)

	# 5. Things that need Dispose: streams, readers, writers, HttpClient, sockets, database contexts, JsonDocument, timers.
	#    A good rule: if you opened it, close it; if the class has a Dispose or Close method, use it.
	? nl + "5. rule: whoever creates a resource releases it, in the same function if possible"

# Opens a reader, fails while reading, and never closes the reader
func readBadly cFile

	oReader = new StreamReader(cFile)
	try
		? "   first line: " + oReader.ReadLine()
		failHere()
		oReader.Dispose()                       # never reached
	catch
		? "   an error: " + left(cCatchError,40)
	done
	return oReader

# The Dispose is after the try block: it runs whether the work failed or not
func readCarefully cFile

	oReader = new StreamReader(cFile)
	try
		? "   first line: " + oReader.ReadLine()
		failHere()
	catch
		? "   an error: " + left(cCatchError,40)
	done
	oReader.Dispose()
	? "   the reader was disposed"

func failHere

	new Int32().Parse("not a number")

# true when the file could be deleted
func tryDelete cFile

	lDeleted = True
	try
		new File().Delete(cFile)
	catch
		lDeleted = False
	done
	if lDeleted
		new File().WriteAllText([ :path = cFile, :contents = "again" ])        # put it back for the next step
	ok
	return lDeleted

func yesNo lValue

	if lValue
		return "yes"
	ok
	return "no"
Output
1. the file is open. Can we delete it now? no

2. after Dispose. Can we delete it now? yes

3. a reader without a clean-up, and an error while reading:
   first line: line 1
   an error: DotNet Error: System.FormatException: Th
   the file is still locked after the error: yes
   (Ring forgot the variable when the function ended, but the .NET reader is still open)

4. the careful way:
   first line: line 1
   an error: DotNet Error: System.FormatException: Th
   the reader was disposed
   the file can be deleted after the error: yes

5. rule: whoever creates a resource releases it, in the same function if possible

How it works#

Locked while open#

Step 1 opens the file and tries to delete it: no, the system refuses, because the file is in use. Step 2 calls Dispose() and now the delete works. A program that forgets this leaves files locked until it ends, and a long-running program (a service, a window) can run out of handles.

An error skips the clean-up#

Step 3 is the typical bug. The function opens a reader, then does some work that fails (here a number that cannot be read), and the line oReader.Dispose() after the failing call is never reached: the file is still locked after the error. Note the comment in the output: Ring forgets the variable when the function ends, but the .NET object is still alive and open. The Ring variable is not the resource.

The careful way#

Step 4 puts the Dispose after the try … catch … done block: it runs whether the work succeeded or failed.

Ring
oReader = new StreamReader(cFile)
try
	work()
catch
	? "an error"
done
oReader.Dispose()                  # always reached

C# has a using statement and finally for this; in Ring the pattern is open → try / catch → dispose after. If the function must return from inside the try, store the result in a variable and return after the dispose.

What needs Dispose#

Streams and readers/writers, HttpClient, sockets and listeners, JsonDocument (the tutorial JSON and XML), database contexts (the tutorial Databases step by step), timers and bitmaps. Rule of thumb: if the class has a Dispose or Close method, use it. Methods that do everything for you in one call (File.ReadAllText, File.WriteAllText) open and close the file themselves — another reason to prefer them for small files.

Tip

Release in the same function that created the resource whenever you can. A resource that travels between functions is a resource that nobody releases.

What you learned#

Exercises#

  1. Write readFirstLine(cFile) that opens a StreamReader, reads a line, disposes it and returns the line — even if the file is empty.
  2. Open the same file twice for writing and see the error message.
  3. Write a function that copies a file with two streams and releases both even if the copy fails.

Next#

Speed — measure first

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.