Block a thread using something other than an object

when using lock, the thing you lock should be an object. For example, this is legal

    static DateTime NextCleanup = DateTime.Now;
    const TimeSpan CleanupInterval = new TimeSpan(1, 0, 0);
    private static void DoCleanup()
    {
        lock ((object)NextCleanup)
        {
            if (NextCleanup < DateTime.Now)
            {
                NextCleanup = DateTime.Now.Add(CleanupInterval);
                System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(cleanupThread));
            }
        }
        return;
    }
+3
source share
4 answers

Keep in mind that even if what you are trying to do here was possible (i.e. if it DateTimewas a reference type and, therefore, something that you could block), it would not be legal because you set NextCleanupto a new value in the block lock.

You cannot link to a new object in a block of code that is locked on that object.

, , .

+6

.

DateTime , .
, Monitor.Enter DateTime, .

?
, , . ( , )
, , .

. CA2002.

+10

, . , System.Threading.Timer, .

+1

System.Object, ?

0

Source: https://habr.com/ru/post/1744215/


All Articles