.Net线程中的关键区域无法正常工作

Ras*_*dit 3 multithreading c#-2.0

我正在尝试运行涉及线程和关键区域的示例代码(非常基本的代码).

这是我的代码:

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();
        }
Run Code Online (Sandbox Code Playgroud)

我称它如下:

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();
        }
Run Code Online (Sandbox Code Playgroud)

但是,我得到的输出是:

**

Start thread
Abort thread
In main
IsValid: True
IsComplete: False
Run Code Online (Sandbox Code Playgroud)

**

由于定义了关键区域,因此IsComplete应该为true而不是false.

有人可以解释为什么它不起作用?

这是SomeClass供参考:

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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

编辑

从MCTS注释:关键区域背后的想法是提供一个必须执行的代码区域,就像它是一条线一样.任何在线程处于关键区域内时中止线程的尝试都必须等到关键区域完成之后.此时,线程将被中止,抛出ThreadAbortException.具有和不具有关键区域的线程之间的差异如下图所示:

关键区域http://www.freeimagehosting.net/uploads/9dd3bb5445.gif

And*_*ite 7

Thread.BeginCriticalRegion不会阻止线程被中止.我相信它用于通知运行时如果线程在关键部分中止,则继续运行application/AppDomain不一定安全.

MSDN文档有一个更完整的解释:http: //msdn.microsoft.com/en-us/library/system.threading.thread.begincriticalregion.aspx