Hi,
I am trying to run a sample code (a very basic one) involving threading and critical regions.
Here's my code:
public static void DoCriticalWork(object o)
{
SomeClass instance = o as SomeClass;
Thread.BeginCriticalRegion();
instance.IsValid = true;
Thread.Sleep(2);
instance.IsComplete = true;
Thread.EndCriticalRegion();
instance.Print();
}
And I am calling it as follows:
private static void CriticalHandled()
{
SomeClass instance = new SomeClass();
ParameterizedThreadStart operation = new ParameterizedThreadStart(CriticalRegion.DoCriticalWork);
Thread t = new Thread(operation);
Console.WriteLine("Start thread");
t.Start(instance);
Thread.Sleep(1);
Console.WriteLine("Abort thread");
t.Abort();
Console.WriteLine("In main");
instance.Print();
}
However, the output I get is:
**
Start thread
Abort thread
In main
IsValid: True
IsComplete: False
**
Since the critical region is defined, IsComplete should be true and not false.
Can someone please explain why it is not working?
Here is SomeClass for reference:
public class SomeClass
{
private bool _isValid;
public bool IsValid
{
get { return _isValid; }
set { _isValid = value; }
}
private bool _isComplete;
public bool IsComplete
{
get { return _isComplete; }
set { _isComplete = value; }
}
public void Print()
{
Console.WriteLine("IsValid: {0}", IsValid);
Console.WriteLine("IsComplete: {0}", IsComplete);
Console.WriteLine();
}
}
Edit
Expln from MCTS notes: The idea behind a critical region is to provide a region of code that must be executed as if it were a single line. Any attempt to abort a thread while it is within a critical region will have to wait until after the critical region is complete. At that point, the thread will be aborted, throwing the ThreadAbortException. The difference between a thread with and without a critical region is illustrated in the following figure: