From 0 self-taught c#13--the problem of locking objects for subclasses and parent class methods

Source: Internet
Author: User
When calling the parent class method, how to be thread safe with the subclass method, which is not the same instance of the lock object, see the following three scenarios.

CASE1:

The following code, when calling the method of the parent class, and the method of the subclass, has a thread safety problem. The instance of the lock object for the reason is not the same.

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Using System.threading;namespace Fortest//check the lock object for thread safety{class program {static Voi            D Main (string[] args) {son myson = new Son ();                 Parallel.For (0, 5, (int i) = = {Myson.methoda ();             MYSON.METHODC ();            });        Console.readkey ();    }} public class Grandfather {//protected static object syncRoot = new Object ();        } public class Father:grandfather {private static object syncRoot = new Object ();        protected int cont = 0;                Public virtual bool MethodA () {lock (syncRoot) {cont++;                Thread.Sleep (1000);                Console.WriteLine ("cout++ is" + cont);            return true;   }} public virtual bool MethodB () {         Lock (SyncRoot) {return true;        }}} public class Son:father {private static object syncRoot = new Object ();                public bool Methodc () {lock (syncRoot) {cont + = 2;                Thread.Sleep (2000);                Console.WriteLine ("Cont + = 2 is" + cont);            return true; }        }    }}

Output:

cout++ is 1cout++ is 4cont + = 2 is 5cout++ are 5cout++ is 8cont + 2 is 9cout++ is 11cont + 2 is 11cont + 2 is 13cont + + 2 is 15

CASE2:

The workaround for CASE1 is to initialize the lock object in the parent class so that the subclass inherits. This will be thread-safe. As follows.

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Using System.threading;namespace Fortest//check the lock object for thread safety{class program {static Voi            D Main (string[] args) {son myson = new Son ();                 Parallel.For (0, 5, (int i) = = {Myson.methoda ();             MYSON.METHODC ();            });        Console.readkey ();    }} public class Grandfather {protected static object SyncRoot = new Object ();        } public class Father:grandfather {protected int cont = 0;                Public virtual bool MethodA () {lock (syncRoot) {cont++;                Thread.Sleep (1000);                Console.WriteLine ("cout++ is" + cont);            return true; }} public virtual bool MethodB () {lock (syncRoot) {RETUrn true;            }}} public class Son:father {public bool Methodc () {Lock (SyncRoot)                {cont + = 2;                Thread.Sleep (2000);                Console.WriteLine ("Cont + = 2 is" + cont);            return true; }        }    }}

Output:

cout++ is 1cout++ is 2cont + = 2 is 4cout++ is 5cout++ are 6cout++ is 7cont + 2 is 9cont + 2 is 11cont + 2 is 13cont + + 2 is 15

CASE3:

Of course there are special cases where subclasses are hard to re-instantiate a lock object. How do I avoid the first thread safety problem above? Need:

Subclass Plus lock override parent class Split method (if parent class MethodA is virtual method)

Or

New (if the parent class MethodA is an instance method).

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Using System.threading;namespace Fortest//check the lock object for thread safety{class program {static Voi            D Main (string[] args) {son myson = new Son ();                 Parallel.For (0, 5, (int i) = = {Myson.methoda ();             MYSON.METHODC ();            });        Console.readkey ();    }} public class Grandfather {protected static object SyncRoot = new Object ();        } public class Father:grandfather {protected int cont = 0;                Public virtual bool MethodA () {lock (syncRoot) {cont++;                Thread.Sleep (1000);                Console.WriteLine ("cout++ is" + cont);            return true; }} public virtual bool MethodB () {lock (syncRoot) {RETUrn true;        }}} public class Son:father {private static object sync = new Object ();            public override bool MethodA ()//override {Lock (sync) {return Base.methoda ();                }} public bool Methodc () {lock (sync) {cont + = 2;                Thread.Sleep (2000);                Console.WriteLine ("Cont + = 2 is" + cont);            return true; }        }    }}

Or

Public new bool MethodA () \\new        {            lock (sync)            {                return Base.methoda ();}        }

Output:

cout++ is 1cout++ is 2cont + = 2 is 4cout++ is 5cout++ are 6cout++ is 7cont + 2 is 9cont + 2 is 11cont + 2 is 13cont + + 2 is 15

The above is from 0 self-taught c#13--subclass and the parent method lock object problem content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.