Click here to Skip to main content
11,648,094 members (70,521 online)
Click here to Skip to main content

Using Keyword Is Not Abort Safe

, 6 Mar 2010 CPOL 49.4K 101 34
Rate this:
Please Sign up or sign in to vote.
This article shows why not even the "using" keyword is a failsafe mechanism

Introduction

C# is a safe and managed language. By safe, we can understand it will help developers avoid common errors, like causing memory leaks or accessing invalid memory. In fact, .NET is really good at this, but the Garbage Collection does not occur immediately so, when we need to free a resource immediately, we must call some type of "free" method, like Close in files and database connections, Commit or Rollback transactions or, in general, the Dispose()method, which is also implemented by files, database objects and transactions.

Dispose() methods free the associated resources immediately, so a file being written can now be read by another process, a database connection can return to the pool and other unmanaged resources (like windows Handles) are freed immediately, releasing memory.

But, how do we call Dispose()?

In C#, we have the using keyword which must be used as follows:

using(var disposable = new DisposableType())
{
  ... do what's needed with the disposable variable here ...
}

And, at the end of the block, the Disposewill be called. Such code will be compiled like:

{
  var disposable = new DisposableType();
  try
  {
    ... do what's needed with the disposable variable here ...
  }
  finally
  {
    if (disposable != null)
      disposable.Dispose();
  }
}

Even the newkeyword will never return null, the "pattern" includes the if (disposable != null), but I really think the JIT will optimize and remove such unnecessary if.

So, this code is safe, right? Any exception after the disposable object is created will be protected by the finallyclause and will call Dispose.

Well, no. For synchronous exceptions, that's correct, but there are asynchronous exceptions too, in special ThreadAbortException.

Imagine that just after setting the disposable value and before the try, a ThreadAbortExceptionis thrown, by a request to Abortfrom another thread. We are not yet in the try, so the finally will not be called. This is an issue. It will not cause a memory leak, considering that GC will eventually collect the object, but such resource will be held for a long time. If this is a database connection, it could not return to the pool. If this is a file, it can be kept in exclusive mode forbidding anyone else from using it.

So, how do we solve this? I will present the solution later, but I will first show something that looks like a solution. Why? Because I think that not knowing the problem with this pseudo solution will make someone try to use it, specially because there are some places that already use this structure as the "right" one.

The Code

DisposableType disposable = null;
try
{
  disposable = new DisposableType();
  ... use the disposable object here ...
}
finally
{
  if (disposable != null)
    disposable.Dispose();
}

In this solution, the disposable is initialized with null. So, the block is protected with a try/finallybefore the disposable object is created. If the ThreadAbortExceptioncomes before object is created, the ifin the finallywill make it work. If the ThreadAbortExceptioncomes just after the object is created, it will work also. But, there is still a problem.

Abort can happen at any assembly instruction. Even our line looks like disposable = new DisposableType(), in assembler we first allocate the type and then we store such result in disposable variable. To make it worse, constructors can also be interrupted in the middle (I made many tests myself, even not having examples to show exactly where the exceptions happen).

So, is there a possible way to solve the problem? Yes. But we must use it with caution. As already shown, when an exception is thrown the finallyblock gets executed. If we are already in the finallyblock, it continues to execute normally, so an Abortcalled for a thread that is already in finallyblock does not force it to exit to another finallyblock, missing some steps. So, we can use this, we put all the code that should not be blocked inside a finallyblock.

But, remember, use it with caution. If you use any blocking operation in such block, you will not be able to Abortthe thread even if you need to. This can be a very frustrating user experience.

So, let's see the code:

DisposableType disposable = null;
try
{
  try
  {
  }
  finally
  {
    disposable = new DisposableType();
  }

  ... use the disposable object here ...
}
finally
{
  if (disposable != null)
    disposable.Dispose();
}

With this solution, or the Aborthappens before the DisposableTypeis allocated, or after it is fully allocated and the variable is set. No "in-the-middle" aborts.

So, this is it? Well, for ThreadAbortExceptions, yes. For other asynchronous exceptions, no. If you look at the documentation of CERs (Constrained Execution Regions), be prepared to deal with the ThreadAbortExceptionis only one of the needed cautions. The system can run out-of-memory when it needs to compile a method or the application can be asked to shutdown abruptly, avoiding normal finallyclauses. But, don't think this makes such a technique obsolete. ThreadAbortExceptionsare much more common than the other exceptions and, specially when the application is shutdown abruptly, files or database connections left open will be reclaimed by the operating system either way.

Improvements

The technique presented works, but it is ugly. So, I decided to create some classes and helper methods. The most important one is in the AbortSafeclass, and is the Runmethod that receives 3 parameters. Let's look at the method:

public static void Run(Action allocationBlock, Action codeBlock, Action finallyBlock)
{
	if (allocationBlock == null)
		throw new ArgumentNullException("allocationBlock");
	
	if (codeBlock == null)
		throw new ArgumentNullException("codeBlock");
	
	if (finallyBlock == null)
		throw new ArgumentNullException("finallyBlock");

	try
	{
		try
		{
		}
		finally
		{
			allocationBlock();
		}
		
		codeBlock();
	}
	finally
	{
		finallyBlock();
	}
}

It simply receives three actions. If the allocation starts, it is guaranteed to finish, even if the abort happens in the middle. Independent from the success of allocation, finalization will be run. The only block that is abortable is the code block.

Let's look a simple example of how to use it:

DisposableType disposable = null;
AbortSafe.Run
(
  () => disposable = new DisposableType(),
  () =>
  {
    ... do what you need with the disposable object...
  },
  () => disposable.CheckedDispose()
);

The CheckedDisposeis an extension method found in Pfz.Extensions.DisposeExtensionsnamespace. It will simply check if the variable is not nullbefore disposing it. I did this only to avoid creating a new code block to do the "if". As you can see, the code is "less" ugly than creating an empty tryto program in the finallyblock. Also, it does not look like an error, so it does not have the same chance of being "corrected" by someone else that does not understand why the code was written in a finallyclause.

Sample

In the attached zip is a program that creates and aborts threads, which will be creating and recreating the same file, but allowing you to choose the way it will do this:

  1. With the usingkeyword
  2. With the pseudo-solution
  3. With the AbortSafesolution

The 1st and 2nd, at some time, will cause an IO exception because the file is "already opened", while the 3rd will not cause such exception.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Paulo Zemek
Engineer Microsoft Corporation
United States United States
I started to program computers when I was 11 years old, as a hobbist, programming in AMOS Basic and Blitz Basic for Amiga.
At 12 I had my first try with assembler, but it was too difficult at the time. Then, in the same year, I learned C and, after learning C, I was finally able to learn assembler (for Motorola 680x0).
Not sure, but probably between 12 and 13, I started to learn C++. I always programmed "in an object oriented way", but using function pointers instead of virtual methods.

At 15 I started to learn Pascal at school and to use Delphi. At 16 I started my first internship (using Delphi). At 18 I started to work professionally using C++ and since then I've developed my programming skills as a professional developer in C++ and C#, generally creating libraries that help other developers do they work easier, faster and with less errors.

Now I just started working as a Senior Software Engineer at Microsoft.

Want more info or simply want to contact me?
Take a look at: http://paulozemek.azurewebsites.net/
Or e-mail me at: paulozemek@outlook.com

Codeproject MVP 2012, 2015
Microsoft MVP 2013-2014

You may also be interested in...

Comments and Discussions

 
QuestionI don't understand the problem described by the first solution Pin
polarboy18-Jan-13 5:10
memberpolarboy18-Jan-13 5:10 
AnswerRe: I don't understand the problem described by the first solution Pin
Paulo Zemek19-Jan-13 6:16
memberPaulo Zemek19-Jan-13 6:16 
GeneralRe: I don't understand the problem described by the first solution Pin
polarboy20-Jan-13 15:35
memberpolarboy20-Jan-13 15:35 
GeneralRe: I don't understand the problem described by the first solution Pin
Paulo Zemek21-Jan-13 5:45
memberPaulo Zemek21-Jan-13 5:45 
GeneralMy vote of 5 Pin
phil.o2-Jan-13 22:28
memberphil.o2-Jan-13 22:28 
GeneralRe: My vote of 5 Pin
Paulo Zemek3-Jan-13 2:36
mvpPaulo Zemek3-Jan-13 2:36 
GeneralOff Topic Pin
OriginalGriff6-Feb-13 6:10
mvpOriginalGriff6-Feb-13 6:10 
GeneralRe: Off Topic Pin
phil.o6-Feb-13 6:17
memberphil.o6-Feb-13 6:17 
OK, no problem, I wasn't aware of Chris' message.
I won't do it anymore.
No memory stick has been harmed during establishment of this signature.

GeneralRe: Off Topic Pin
OriginalGriff6-Feb-13 6:31
mvpOriginalGriff6-Feb-13 6:31 
GeneralMy vote of 5 Pin
Ivaylo5ev4-Sep-12 8:27
memberIvaylo5ev4-Sep-12 8:27 
GeneralRe: My vote of 5 Pin
Paulo Zemek3-Jan-13 2:36
mvpPaulo Zemek3-Jan-13 2:36 
GeneralMy vote of 4 Pin
Patrick Kalkman21-Apr-11 5:23
memberPatrick Kalkman21-Apr-11 5:23 
GeneralTwo-step object creation Pin
supercat98-Mar-10 6:02
membersupercat98-Mar-10 6:02 
GeneralRe: Two-step object creation [modified] Pin
Paulo Zemek9-Mar-10 7:21
memberPaulo Zemek9-Mar-10 7:21 
GeneralMy Vote of 3: No Proof Pin
aspdotnetdev5-Dec-09 12:35
memberaspdotnetdev5-Dec-09 12:35 
GeneralRe: My Vote of 3: No Proof Pin
Paulo Zemek7-Dec-09 1:03
memberPaulo Zemek7-Dec-09 1:03 
GeneralRe: My Vote of 3: No Proof Pin
Paulo Zemek7-Dec-09 1:11
memberPaulo Zemek7-Dec-09 1:11 
GeneralRe: My Vote of 3: No Proof Pin
aspdotnetdev7-Dec-09 4:55
memberaspdotnetdev7-Dec-09 4:55 
GeneralRe: My Vote of 3: No Proof Pin
aspdotnetdev7-Dec-09 6:51
memberaspdotnetdev7-Dec-09 6:51 
GeneralRe: My Vote of 3: No Proof Pin
aspdotnetdev7-Dec-09 4:58
memberaspdotnetdev7-Dec-09 4:58 
GeneralRe: My Vote of 3: No Proof Pin
Paulo Zemek7-Dec-09 6:41
memberPaulo Zemek7-Dec-09 6:41 
GeneralRe: My Vote of 3: No Proof Pin
aspdotnetdev7-Dec-09 6:49
memberaspdotnetdev7-Dec-09 6:49 
GeneralRe: My Vote of 3: No Proof [modified] Pin
Paulo Zemek7-Dec-09 7:03
memberPaulo Zemek7-Dec-09 7:03 
GeneralRe: My Vote of 3: No Proof Pin
aspdotnetdev7-Dec-09 8:29
memberaspdotnetdev7-Dec-09 8:29 
GeneralRe: My Vote of 3: No Proof [modified] Pin
Paulo Zemek7-Dec-09 9:41
memberPaulo Zemek7-Dec-09 9:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150804.4 | Last Updated 6 Mar 2010
Article Copyright 2009 by Paulo Zemek
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid