Search code examples
.netgraphicsconcurrencysystem.drawinginvalidoperationexception

How to prevent InvalidOperationException when using System.Drawing.Graphics?


I am using the System.Drawing.Graphics.DrawLines(Pen pen, PointF[] points) method in a multithreaded application, but the System.Drawing.Graphics isn't shared between threads.

Why it keeps throwing the System.InvalidOperationException: The object is currently in use elsewhere ?


Solution

  • The problem was: I was using the same System.Drawing.Pen instance for all threads. I had to clone it for every thread in order to solve the problem.

    var pens = new Pen[0];
    lock (this._pens)
    {
        pens = (Pen[])this._pens.Select(a => (Pen) a.Clone()).ToArray();
    }
    

    Even the lock is essential in order to solve this problem