백엔드 개발 C#.Net 튜토리얼 0에서 C#13 자가 학습 - 하위 클래스 및 상위 클래스 메서드의 개체 잠금 문제

0에서 C#13 자가 학습 - 하위 클래스 및 상위 클래스 메서드의 개체 잠금 문제

Feb 04, 2017 am 11:14 AM

调用父类方法时,如何与子类方法,在锁对象不是同一个实例下,能线程安全,请见下面三种情况。

case1:

如下代码,在调用父类的方法时,和子类的方法,发生线程安全问题。原因的锁对象的实例不是同一个。

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 void 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;
            }
        }
    }
}
로그인 후 복사

输出:

cout++ is 1
cout++ is 4
cont += 2 is 5
cout++ is 5
cout++ is 8
cont += 2 is 9
cout++ is 11
cont += 2 is 11
cont += 2 is 13
cont += 2 is 15
로그인 후 복사

case2:

case1的解决方法是,在父类初始化锁对象,让子类继承。这样就线程安全了。如下。

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 void 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;
            }
        }
    }
}
로그인 후 복사

输出:

cout++ is 1
cout++ is 2
cont += 2 is 4
cout++ is 5
cout++ is 6
cout++ is 7
cont += 2 is 9
cont += 2 is 11
cont += 2 is 13
cont += 2 is 15
로그인 후 복사
로그인 후 복사

case3:

当然有些特殊情况下,子类硬要重新实例化一个锁对象。如何避免上面第一种线程安全问题发生?需要:

子类加锁重写父类分方法(如果父类methodA是虚方法)

或者

new一下(如果父类methodA是实例方法)。

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 void 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()//重写
        {            lock (sync)
            {                return base.methodA();
            }
        }        public bool methodC()
        {            lock (sync)
            {
                cont += 2;
                Thread.Sleep(2000);
                Console.WriteLine("cont += 2 is " + cont);                return true;
            }
        }
    }
}
로그인 후 복사

 public new bool methodA()\\new一下
        {            lock (sync)
            {                return base.methodA();
            }
        }
로그인 후 복사

输出:

cout++ is 1
cout++ is 2
cont += 2 is 4
cout++ is 5
cout++ is 6
cout++ is 7
cont += 2 is 9
cont += 2 is 11
cont += 2 is 13
cont += 2 is 15
로그인 후 복사
로그인 후 복사

以上就是 从0自学C#13--子类和父类方法的锁对象问题的内容,更多相关内容请关注PHP中文网(www.php.cn)!


본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

C#을 사용한 Active Directory C#을 사용한 Active Directory Sep 03, 2024 pm 03:33 PM

C#을 사용한 Active Directory 가이드. 여기에서는 소개와 구문 및 예제와 함께 C#에서 Active Directory가 작동하는 방식에 대해 설명합니다.

C#의 난수 생성기 C#의 난수 생성기 Sep 03, 2024 pm 03:34 PM

C#의 난수 생성기 가이드입니다. 여기서는 난수 생성기의 작동 방식, 의사 난수 및 보안 숫자의 개념에 대해 설명합니다.

C#의 액세스 한정자 C#의 액세스 한정자 Sep 03, 2024 pm 03:24 PM

C#의 액세스 수정자에 대한 안내입니다. 예제 및 출력과 함께 C#의 액세스 한정자의 소개 유형에 대해 논의했습니다.

C# 데이터 그리드 보기 C# 데이터 그리드 보기 Sep 03, 2024 pm 03:32 PM

C# 데이터 그리드 뷰 가이드. 여기서는 SQL 데이터베이스 또는 Excel 파일에서 데이터 그리드 보기를 로드하고 내보내는 방법에 대한 예를 설명합니다.

C# 직렬화 C# 직렬화 Sep 03, 2024 pm 03:30 PM

C# 직렬화 가이드. 여기에서는 C# 직렬화 개체의 소개, 단계, 작업 및 예제를 각각 논의합니다.

C#의 패턴 C#의 패턴 Sep 03, 2024 pm 03:33 PM

C#의 패턴 가이드. 여기에서는 예제 및 코드 구현과 함께 C#의 패턴 소개 및 상위 3가지 유형에 대해 설명합니다.

C#의 소수 C#의 소수 Sep 03, 2024 pm 03:35 PM

C#의 소수 가이드. 여기서는 코드 구현과 함께 C#의 소수에 대한 소개와 예를 논의합니다.

C#의 팩토리얼 C#의 팩토리얼 Sep 03, 2024 pm 03:34 PM

C#의 팩토리얼 가이드입니다. 여기서는 다양한 예제 및 코드 구현과 함께 C#의 계승에 대한 소개를 논의합니다.

See all articles