Sample code to illustrate a deadlock by using lock(this)

前端 未结 6 1169
我在风中等你
我在风中等你 2020-12-23 20:57

I\'ve read several articles and posts that say that lock(this), lock(typeof(MyType)), lock(\"a string\") are all bad practice because

6条回答
  •  心在旅途
    2020-12-23 21:31

    The problem is that lock("a string") is locking on a singleton. This means that other objects that use the same lock could be an infinite wait.

    for example:

    using System;
    using System.Threading;
    
    namespace ThreadLock
    {
        class Program
        {
            static void Main(string[] args)
            {
                lock ("my lock")
                {
                    ManualResetEvent evt = new ManualResetEvent(false);
                    WorkerObject worker = new WorkerObject(evt);
                    Thread t = new Thread(new ThreadStart(worker.Work));
                    t.Start();
                    evt.WaitOne();
                }
            }
        }
    
        class WorkerObject
        {
            private ManualResetEvent _evt;
            public WorkerObject(ManualResetEvent evt)
            {
                _evt = evt;
            }
            public void Work()
            {
                lock ("my lock")
                {
                    Console.WriteLine("worked.");
                    _evt.Set();
                }
            }
        }
    }
    

    In this case, the calling code creates a lock on a string then makes a worker object. The worker object in Work() locks on the same string, which is a singleton in C#. It ends up in deadlock because the caller owns the lock and is waiting for a signal which will never come.

提交回复
热议问题