⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 broken.cs

📁 Microsoft?Visual C#?.NET (Core Reference)
💻 CS
字号:
using System;
using System.Threading;
using System.Collections;

namespace MSPress.CSharpCoreRef.Threads
{
    public class Broken
    {
        const int MaxLoops = 20000;
        protected long dangerousVariable = 0;

        protected void UpdateMethod()
        {
            //Monitor.Enter(this);
            dangerousVariable++;
            //Monitor.Exit(this);
        }

        public long Result
        {
            get { return dangerousVariable; }
        }

        public void ThreadProc()
        {
            for(int n = 0; n < MaxLoops; ++n)
            {
                UpdateMethod();
                Console.Write(".");
            }
        }

        public void TakeALock()
        {
            try
            {
                Monitor.Enter(this);
                ThrowAnException();
                Monitor.Exit(this);
            }
            catch
            {
                Console.WriteLine("Caught an exception");
            }
        }

        public void SimpleLock()
        {
            lock(this)
            {
                ThrowAnException();
            }
        }

        public void ImprovedTakeALock()
        {
            try
            {
                Monitor.Enter(this);
                ThrowAnException();
            }
            catch
            {
                Console.WriteLine("Caught an exception");
            }
            finally
            {
                Monitor.Exit(this);
            }
        }

        public void TryToPrintMessage()
        {
            Monitor.Enter(this);
            Console.WriteLine("Can you see this");
            Monitor.Exit(this);
        }

        private void ThrowAnException()
        {
            throw new InvalidOperationException("Bypass monitor code");
        }

    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -