Jason Crease

Test Engineer - Red Gate Software

A Quick .NET Puzzle

Published Thursday, July 17, 2008 6:17 PM

Just a quick .NET puzzle.  Does this application ever throw that ApplicationException?  If so, why?


using System;
using System.Threading;

class Program
{
    
static long Num = 0;

    
static void Main(string[] args)
    
{
        Thread t1
= new Thread(ModifyNum);
        
t1.Start();
        
while (true)
        
{
            
long k = Num;
            
if (k != -&& k != 0) throw new ApplicationException(
                
"k is not -1 or 0.  It is " + k.ToString());
        
}
    }

    
static void ModifyNum()
    
{
        while
(true)
        
{
            
if (Num == -1) Num = 0;
            
else Num = -1;
        
}
    }
}

Stuck?  Then here's a hint: if you change Num from a long to an int, it never throws the exception.

Comments

 

James Hart said:

Ah yes - this little bit of CLR weirdness. As another hint, it never throws an exception on my computer. But then I am running a 64bit OS. If I compile that code with a processor target of x86, though...
July 18, 2008 3:59 AM
 

Jason Crease said:

Ah, yes I forgot to mention that!  Thanks James.
July 18, 2008 5:54 AM
 

Melvyn.Harbour said:

or if you use Interlocked.Exchange...
July 22, 2008 8:00 AM
You need to sign in to comment on this blog

About Jason Crease

Jason Crease joined Red-Gate in 2006, and works as a software tester in the .NET division. He is currently working on ANTS Profiler 4.

















<July 2008>
SuMoTuWeThFrSa
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789
Virtual Exchange Servers
 Microsoft now supports running Exchange Server 2007 in server virtualization environments, not just on... Read more...

Virtualizing Exchange: points for discussion
 With the increasing acceptance of the use of Virtualization as a means of providing server... Read more...

Encouraging .NET Reflector Add-ins
 Jason Haley is well-known for the resources he's provided to developers who wish to extend Reflector's... Read more...

Using .NET Reflector Add-ins
 .NET Reflector by itself is great, but it really comes into its own with the help of some add-ins. Here... Read more...

Unique Experiences!
 You'd have thought that a unique constraint was an easy concept - Not a bit of it; it can cause a lot... Read more...