Do I need to Dispose a SemaphoreSlim?

If you access the AvailableWaitHandle property, then Yes, you must call Dispose() to cleanup unmanaged resources. If you do not access AvailableWaitHandle, then No, calling Dispose() won’t do anything important. SemaphoreSlim will create a ManualResetEvent on demand if you access the AvailableWaitHandle. This may be useful, for example if you need to wait on multiple …

Read more

using statement FileStream and / or StreamReader – Visual Studio 2012 Warnings

The following is how Microsoft recommends doing it. It is long and bulky, but safe: FileStream fs = null; try { fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); using (TextReader tr= new StreamReader(fs)) { fs = null; // Code here } } finally { if (fs != null) fs.Dispose(); } This method will always ensure …

Read more

C# how to implement Dispose method

Question 1: Implement IDisposable as well, using the following pattern: public class MyClass : IDisposable { bool disposed; protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { //dispose managed resources } } //dispose unmanaged resources disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } Question 2: What Microsoft means …

Read more

Dispose vs Dispose(bool)

IDisposable provides a method with the signature public void Dispose() Microsoft best practices (Implement a Dispose method) recommend making a second private method with the signature private void Dispose(bool) Your public Dispose method and finalizer should call this private Dispose method to prevent disposing managed resources multiple times. You can fix the warning you are …

Read more

“Object can be disposed of more than once” error

I struggled with this problem and found the example here to be very helpful. I’ll post the code for a quick view: using (Stream stream = new FileStream(“file.txt”, FileMode.OpenOrCreate)) { using (StreamWriter writer = new StreamWriter(stream)) { // Use the writer object… } } Replace the outer using statement with a try/finally making sure to …

Read more