CPU 100% 問題分析,我們把博客園踩過的坑又踩了一遍《二》

問題如下:

1、StackExchange.Redis.RedisConnectionException: It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail. Timeout
at StackExchange.Redis.ConnectionMultiplexer.ConnectImpl(Func`1 multiplexerFactory, TextWriter log)

2、There is already an open DataReader associated with this Command which must be closed first

3、A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext, however instance members are not guaranteed to be

static void Main(string[] args)
        {
          //按鍵後開始執行
            Console.ReadKey();
            //模擬並發
            while (true)
            {
                Task.Run(Producer);
                Thread.Sleep(200);
            }
           
        }
        /// <summary>
        /// 如果處理程序耗時>請求耗時,也就是說引起並發,就會導致死鎖
        /// </summary>
        static void Producer()
        {
            var result = Process().Result;
            //或者
            //Process().Wait();
        }


        static async Task<bool> Process()
        {
            Console.WriteLine("Start - " + DateTime.Now.ToLongTimeString());
            await Task.Run(() =>
            {
                //模擬任務執行耗時
                Thread.Sleep(1000);
            });

            Console.WriteLine("Ended - " + DateTime.Now.ToLongTimeString());
            return true;
        }        

 

執行效果:

以上可看出:

1、控制台執行5-10個任務後,不再執行Ended 語句的任何內容(Ended語句全部被阻塞)

2、內存佔用穩步上升

3、AsyncTest.exe 線程每秒增加一個

 

解決方案:

var result = Process().ConfigureAwait(false);

或修改為異步方法

     static async Task Producer()
        {
            await Process();
        }

 

 

參考:

又踩.NET Core的坑:在同步方法中調用異步方法Wait時發生死鎖(deadlock)

一碼阻塞,萬碼等待:ASP.NET Core 同步方法調用異步方法「死鎖」的真相

.NET Core中遇到奇怪的線程死鎖問題:內存與線程數不停地增長

 C#同步方法中如何調用異步方法?值得一看

 理解C#中的ConfigureAwait

 bindot://www.cnblogs.com/bindot/p/cpu100.html