{"record":{"id":"df10ba5f364365ef","repo":"dotnet/wpf","slug":"sr-image-mustbelocked-writeablebitmap","errorCode":null,"errorMessage":"SR.Image_MustBeLocked","messagePattern":"SR\\.Image_MustBeLocked","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/PresentationCore/System/Windows/Media/Imaging/WriteableBitmap.cs","lineNumber":160,"sourceCode":"        /// </summary>\n        /// <param name=\"dirtyRect\">\n        ///   An Int32Rect structure specifying the dirty region.\n        /// </param>\n        /// <remarks>\n        ///   This method can be called multiple times, and the areas are accumulated\n        ///   in a sufficient, but not necessarily minimal, representation.  For efficiency,\n        ///   only the areas that are marked as dirty are guaranteed to be copied over to\n        ///   the rendering system.\n        ///   AddDirtyRect can only be called while the bitmap is locked, otherwise an\n        ///   InvalidOperationException will be thrown.\n        /// </remarks>\n        public void AddDirtyRect(Int32Rect dirtyRect)\n        {\n            WritePreamble();\n\n            if (_lockCount == 0)\n            {\n                throw new InvalidOperationException(SR.Image_MustBeLocked);\n            }\n\n            //\n            // Sanitize the dirty rect.\n            //\n            dirtyRect.ValidateForDirtyRect(nameof(dirtyRect), _pixelWidth, _pixelHeight);\n            if (dirtyRect.HasArea)\n            {\n                MILSwDoubleBufferedBitmap.AddDirtyRect(\n                    _pDoubleBufferedBitmap,\n                    ref dirtyRect);\n\n                _hasDirtyRects = true;\n            }\n\n            // Note: we do not call WritePostscript because we do not want to\n            // raise change notifications until the writeable bitmap is unlocked.\n        }","sourceCodeStart":142,"sourceCodeEnd":178,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/PresentationCore/System/Windows/Media/Imaging/WriteableBitmap.cs#L142-L178","documentation":"AddDirtyRect may only be called between TryLock/BeginInit lock acquisition and Unlock. WritePreamble plus the _lockCount == 0 check throw InvalidOperationException with SR.Image_MustBeLocked when the bitmap is not currently locked.","triggerScenarios":"Calling AddDirtyRect before Lock/TryLock (or after Unlock), or on a bitmap created via the constructor without ever locking.","commonSituations":"Updating pixels outside the using/Lock scope; forgetting Lock after re-creating the bitmap; calling AddDirtyRect from another thread that didn't lock.","solutions":["Wrap the update in using (wb.Lock()) { ... wb.AddDirtyRect(rect); }","Check that Lock/TryLock succeeded (TryLock returns false when another thread holds the lock) before calling AddDirtyRect","Ensure Unlock is not called before all AddDirtyRect calls complete","Perform lock/AddDirtyRect/Unlock on the same thread that owns the lock"],"exampleFix":"// before\nwb.AddDirtyRect(new Int32Rect(0, 0, 10, 10)); // throws: not locked\n// after\nusing (wb.Lock())\n{\n    // write pixels...\n    wb.AddDirtyRect(new Int32Rect(0, 0, 10, 10));\n}","handlingStrategy":"try-catch","validationCode":"// call only inside a lock scope\nusing (wb.Lock())\n{\n    wb.AddDirtyRect(rect);\n}","typeGuard":"// no type guard; check lock state by structuring code inside Lock scope\nstatic void SafeAddDirtyRect(WriteableBitmap wb, Int32Rect r)\n{\n    using (wb.Lock()) { wb.AddDirtyRect(r); }\n}","tryCatchPattern":"try { wb.AddDirtyRect(rect); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"lock\"))\n{\n    using (wb.Lock()) { wb.AddDirtyRect(rect); }\n}","preventionTips":["Always pair Lock/Unlock (or use the Lock() disposable) around AddDirtyRect","Never call AddDirtyRect after Unlock; batch all rect updates in one lock scope","With TryLock, check the bool return before proceeding","Keep bitmap updates on the thread that owns the lock"],"tags":["wpf","bitmap","invalidoperationexception","threading","lock"],"backgroundTag":"invalid-state-transition","analyzedSha":"81131a70a4c573cd62748a5c36908fc4d662daa9","analyzedAt":"2026-09-14T10:12:48.479Z","contentChangedAt":"2026-09-14T10:12:48.479Z","schemaVersion":2},"datasetVersion":"2026-09-22T01:17:13.364Z"}