Lock thread using somthing other than a object

Posted by Scott Chamberlain on Stack Overflow See other posts from Stack Overflow or by Scott Chamberlain
Published on 2010-05-05T18:19:17Z Indexed on 2010/05/05 18:28 UTC
Read the original article Hit count: 277

Filed under:
|
|

when using a lock does the thing you are locking on have to be a object. For example is this 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;
    }

EDIT-- From reading SLaks' responce I know the above code would be not valid but would this be?

    static MyClass myClass = new MyClass();
    private static void DoCleanup()
    {
        lock (myClass)
        {
            //
        }
        return;
    }

© Stack Overflow or respective owner

Related posts about c#

Related posts about locking