c # multithreading lock invalid

 When writing windows service need to use multiple threads to run data, with lock to lock a section of code execution method, after logging found to be invalid, did not work.

 program code is as follows:

///  <Summary> 
        /// main entry point for the application
         ///  </ Summary> 
        static  void the Main ()
        {
            . Log4Helper.GetInstance () Info ( " service start " );
             the try
            {
                ThreadPool.QueueUserWorkItem(PushCache, new SearchParam() { MsgType = 3 });
                ThreadPool.QueueUserWorkItem(PushCache, new SearchParam() { MsgType = 3 });
                ThreadPool.QueueUserWorkItem(PushCache, new SearchParam() { MsgType = 3 });
                ThreadPool.QueueUserWorkItem(PushCache, new SearchParam() { MsgType = 3 });
                ThreadPool.QueueUserWorkItem(PushCache, new SearchParam() { MsgType = 3 });
                SleepTime the TimeSpan = new new the TimeSpan ( . 1 , 0 , 0 ); // Sleep one hour 
                the while ( to true )
                {
                    Thread.Sleep(sleepTime);
                }
            }
            catch (Exception e)
            {
                Log4Helper.GetInstance().Error(e);
            }
        }

public static void PushCache(object obj)
        {
            var search = obj as SearchParam;
            MessageCacheBll.GetInstance().PushCache(search);
        }


public class SearchParam
{
/// <summary>
/// 消息类型
/// </summary>
public int MsgType { get; set; }
}

 

MessageCacheBll categories as follows:

public  class MessageCacheBll
    {
        private readonly object _lockThread = new object();

        #region Instance

        private static MessageCacheBll _instance;

        public static MessageCacheBll GetInstance()
        {
            return _instance ?? (_instance = new MessageCacheBll());
        }

        #endregion

        ///  <Summary> 
        /// according to the message type data and histological sections run
         ///  </ Summary> 
        ///  <param name = "Search"> msgType Message type </ param> 
        public  void PushCache ( Object obj)
        {
            var search = (obj as SearchParam) ?? new SearchParam();
            try
            {
                var sqlWhere = "";
                if (search.MsgType == -1)
                {
                    arbitrary SQL WHERE + = " and spm.type in (1,3,4,5,6,100) " ; // . 1 system messages, message 3, 4 operation, notification grades 5, 6 leave, grade 100 with a notification Outbox 
                }
                 else
                {
                    sqlWhere += string.Format(" and spm.type={0} ", search.MsgType);
                }
                List <SpMessageDto> List = new new List <SpMessageDto> ();
                 var updateCacheStatusResult = to false ; // update the buffer status results
                 // lock acquisition run current thread data 
                try
                {
                    lock (_lockThread)
                    {
                        Log4Helper.GetInstance().Info(string.Format("--------lock-开始 threadid{0}--------",
                            Thread.CurrentThread.ManagedThreadId));
                        list = MessageCacheDal.GetInstance().GetNoCacheMessageList(sqlWhere);
                        if (list != null && list.Count > 0)
                        {
                            var idList = list.Select(t => t.Id).ToList();
                            updateCacheStatusResult = MessageCacheDal.GetInstance()
                                .UpdateMessageCacheStatus((int)AppEnum.CacheStatus.Caching, idList);
                        }

                        Log4Helper.GetInstance().Info(string.Format("--------lock-结束 threadid{0}--------",
                            Thread.CurrentThread.ManagedThreadId));
                    }
                }
                catch (Exception e)
                {
                    Log4Helper.GetInstance().Error(e);
                }
            }
            catch (Exception e)
            {
                Log4Helper.GetInstance().Error(string.Format("异常 msgType:{0}。", search.MsgType), e);
            }
        }
    }
}

Log output:

2020-01-0111: 36: 02,872 service starts

2020-01-01 11: 36: 02,882 -------- lock- start threadid4 --------

2020-01-01 11: 36: 02,884 -------- lock- start threadid5 --------

2020-01-01 11: 36: 02,884 -------- lock- start threadid7 --------

2020-01-01 11: 36: 02,884 -------- lock- start threadid3 --------

2020-01-01 11: 36: 03,325 -------- lock- end threadid3 --------

2020-01-01 11: 36: 03,363 -------- lock- end threadid7 --------

2020-01-01 11: 36: 03,367 -------- lock- end threadid4 --------

2020-01-01 11: 36: 03,368 -------- lock- start threadid6 --------

2020-01-01 11: 36: 03,370 -------- lock- end threadid5 --------

2020-01-01 11: 36: 03,595 -------- lock- end threadid6 --------

 

solution:

Method a: Method PushCache remove the program, main direct method calls MessageCacheBll.GetInstance () PushCache (search).

Sample code:

///  <Summary> 
        /// main entry point for the application
         ///  </ Summary> 
        static  void the Main ()
        {
            . Log4Helper.GetInstance () Info ( " service start " );
             the try
            {
                ThreadPool.QueueUserWorkItem(MessageCacheBll.GetInstance().PushCache, new SearchParam() { MsgType = 3 });
                ThreadPool.QueueUserWorkItem(MessageCacheBll.GetInstance().PushCache, new SearchParam() { MsgType = 3 });
                ThreadPool.QueueUserWorkItem(MessageCacheBll.GetInstance().PushCache, new SearchParam() { MsgType = 3 });
                ThreadPool.QueueUserWorkItem(MessageCacheBll.GetInstance().PushCache, new SearchParam() { MsgType = 3 });
                ThreadPool.QueueUserWorkItem(MessageCacheBll.GetInstance().PushCache, new SearchParam() { MsgType = 3 });
                SleepTime the TimeSpan = new new the TimeSpan ( . 1 , 0 , 0 ); // Sleep one hour 
                the while ( to true )
                {
                    Thread.Sleep(sleepTime);
                }
            }
            catch (Exception e)
            {
                Log4Helper.GetInstance().Error(e);
            }
        }

 

Log output:

2020-01-0111: 52: 47,016 service starts

2020-01-01 11: 52: 47,027 -------- lock- start threadid3 --------

2020-01-01 11: 52: 47,508 -------- lock- end threadid3 --------

2020-01-01 11: 52: 47,508 -------- lock- start threadid4 --------

2020-01-01 11: 52: 47,852 -------- lock- end threadid4 --------

2020-01-01 11: 52: 47,852 -------- lock- start threadid5 --------

2020-01-01 11: 52: 48,038 -------- lock- end threadid5 --------

2020-01-01 11: 52: 48,038 -------- lock- start threadid6 --------

2020-01-01 11: 52: 48,292 -------- lock- end threadid6 --------

2020-01-01 11: 52: 48,292 -------- lock- start threadid7 --------

2020-01-01 11: 52: 48,413 -------- lock- end threadid7 --------

 

Method 2: MessageCacheBll PushCache into the program in, lock also placed in the program

Sample code:

static class Program
    {
        ///  <Summary> 
        /// main entry point for the application
         ///  </ Summary> 
        static  void the Main ()
        {
            . Log4Helper.GetInstance () Info ( " service start " );
             the try
            {
                ThreadPool.QueueUserWorkItem(PushCache, new SearchParam() { MsgType = 3 });
                ThreadPool.QueueUserWorkItem(PushCache, new SearchParam() { MsgType = 3 });
                ThreadPool.QueueUserWorkItem(PushCache, new SearchParam() { MsgType = 3 });
                ThreadPool.QueueUserWorkItem(PushCache, new SearchParam() { MsgType = 3 });
                ThreadPool.QueueUserWorkItem(PushCache, new SearchParam() { MsgType = 3 });
                SleepTime the TimeSpan = new new the TimeSpan ( . 1 , 0 , 0 ); // Sleep one hour 
                the while ( to true )
                {
                    Thread.Sleep(sleepTime);
                }
            }
            catch (Exception e)
            {
                Log4Helper.GetInstance().Error(e);
            }
        }

        Private  static  Readonly  Object _lockThread = new new  Object ();
         ///  <Summary> 
        /// according to the message type data and histological sections run
         ///  </ Summary> 
        ///  <param name = "Search"> msgType message type < / param> 
        public  static  void PushCache ( Object obj)
        {
            var search = (obj as SearchParam) ?? new SearchParam();
            try
            {
                var sqlWhere = "";
                if (search.MsgType == -1)
                {
                    sqlWhere += " and spm.type in(1,3,4,5,6,100) ";
                }
                else
                {
                    sqlWhere += string.Format(" and spm.type={0} ", search.MsgType);
                }
                List <SpMessageDto> List = new new List <SpMessageDto> ();
                 var updateCacheStatusResult = to false ; // update the buffer status results
                 // lock acquisition run current thread data 
                try
                {
                    lock (_lockThread)
                    {
                        Log4Helper.GetInstance().Info(string.Format("--------lock-开始 threadid{0}--------",
                            Thread.CurrentThread.ManagedThreadId));
                        list = MessageCacheDal.GetInstance().GetNoCacheMessageList(sqlWhere);
                        if (list != null && list.Count > 0)
                        {
                            var idList = list.Select(t => t.Id).ToList();
                            updateCacheStatusResult = MessageCacheDal.GetInstance()
                                .UpdateMessageCacheStatus((int)AppEnum.CacheStatus.Caching, idList);
                        }

                        Log4Helper.GetInstance().Info(string.Format("--------lock-结束 threadid{0}--------",
                            Thread.CurrentThread.ManagedThreadId));
                    }
                }
                catch (Exception e)
                {
                    Log4Helper.GetInstance().Error(e);
                }
            }
            catch (Exception e)
            {
                Log4Helper.GetInstance().Error(string.Format("异常 msgType:{0}。", search.MsgType), e);
            }
        }

 

 

Log output record:

2020-01-0111: 57: 35,878 service starts

2020-01-01 11: 57: 35,888 -------- lock- start threadid4 --------

2020-01-01 11: 57: 36,586 -------- lock- end threadid4 --------

2020-01-01 11: 57: 36,586 -------- lock- start threadid6 --------

2020-01-01 11: 57: 36,789 -------- lock- end threadid6 --------

2020-01-01 11: 57: 36,789 -------- lock- start threadid3 --------

2020-01-01 11: 57: 37,186 -------- lock- end threadid3 --------

2020-01-01 11: 57: 37,186 -------- lock- start threadid5 --------

2020-01-01 11: 57: 37,279 -------- lock- end threadid5 --------

2020-01-01 11: 57: 37,279 -------- lock- start threadid7 --------

2020-01-01 11: 57: 37,394 -------- lock- end threadid7 --------

 

Guess you like

Origin www.cnblogs.com/jiangqw/p/12128497.html