I've been doing some optimization for the following piece of code :

public void DrawLine(int x1, int y1, int x2, int y2, int color)
    _bitmap.DrawLineBresenham(x1, y1, x2, y2, color);

After profiling it about 70% of the time spent was in getting a context for drawing and disposing it.

I ended up sketching the following overload :

public void DrawLine(int x1, int y1, int x2, int y2, int color, BitmapContext bitmapContext)
    _bitmap.DrawLineBresenham(x1, y1, x2, y2, color, bitmapContext);

Until here no problems, all the user has to do is to pass a context and performance is really great as a context is created/disposed one time only (previously it was a thousand times per second).

The next step was to make it generic in the sense it doesn't depend on a particular framework for rendering (besides .NET obvisouly).

So I wrote this method :

public void DrawLine(int x1, int y1, int x2, int y2, int color, IDisposable bitmapContext)
    _bitmap.DrawLineBresenham(x1, y1, x2, y2, color, (BitmapContext)bitmapContext);

Now every time a line is drawn the generic context is casted, this was unexpected for me.

Are there any approaches for fixing this design issue ?

Note :

  • 1
    Making your bitmapContext as an IDisposable input is probably a really bad idea. There's many many many IDisposable classes and they'll all be valid, until your try to cast them and then you'll have some major issues. You would better be served by making an specific interface that DrawLineBresenham will accept for it's needed methods and require that.
    – siva.k
    Aug 24, 2014 at 20:35

2 Answers 2


I fixed it by doing the following : 2 methods like in OpenGL to call before/after drawing operations.

public void RenderBegin()
    _context = _bitmap.GetBitmapContext();

public void RenderEnd()

No need for an extra DrawLine overload and obviously the method uses the context every time.

But no more ugly cast at every call :D


I would implement it so context is created when DrawLine is called for the first time and make the whole class IDisposable and dispose the context in there, it if was created of course.

  • Sorry I should have added more details, that won't work since to kick an image refresh the context must be disposed. Apr 26, 2014 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.