.Net Critical areas in the stream do not work as desired

I am trying to run a sample code (very simple) that includes threads and critical areas.

Here is 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 call it this way:

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, I get:

**

Start thread
Abort thread
In main
IsValid: True
IsComplete: False

**

Since a critical area is defined, IsComplete must be true, not false.

Can someone explain why it is not working?

Here is a SomeClass reference 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

MCTS: , , , . , , , . , ThreadAbortException. :

http://www.freeimagehosting.net/uploads/9dd3bb5445.gif

+3
3

Thread.BeginCriticalRegion Thread. , , Thread , /AppDomain.

MSDN : http://msdn.microsoft.com/en-us/library/system.threading.thread.begincriticalregion.aspx

+7

. , .

: , . , , t , .

, 2 t 1 , t , . , IsComplete , .

, 100 , , IsComplete . , "t", 100 , , IsComplete .

FROM MSDN

, , .

, , , . , , AppDomain, , . , .

, AppDomain, . , , BeginCriticalRegion. EndCriticalRegion, .


CLR Inside Out:

, . - , , . - , , AppDomain, , , . . - , , , , .

, , - , . , . , , . . AppDomain, AppDomain. , AppDomain, . , , AppDomain .

, .

+1

DoCriticalWork()


try { ... } catch(ThreadAbortedException) {...}


( , IsComplete = true?)

ThreadAbortException Thread.ResetAbort finally .

Thread.BeginCriticalRegion:

Tells the node that execution should enter a region of code in which the consequences of a thread interruption or an unhandled exception could jeopardize other tasks in the application domain.

0
source

Source: https://habr.com/ru/post/1731140/


All Articles