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
Go With the Flow
 Knowing enough about the routes that messages take is vital to being an effective Exchange admin,... Read more...

When Email Collaboration Could Have Changed History
 In our mission to make history relevant to the busy IT executive, we speculate how Email might have... Read more...

Bunnikins!
 When an IT manager is selected as a victim of office politics of a large corporate, it is time for him... Read more...

Exchange Database Technologies
 One of the most misunderstood technologies in Exchange Server, regardless of its version, is the... Read more...

Top Tips for Exchange Admins
 Michael Francis hands out imaginary Olympic medals to the winner of the August 'Top Tips for Exchange... Read more...