Search code examples
c#multithreadingopenglopentk

OpenTK multithreading?


Is there a way to draw to the screen using OpenTK/OpenGL in another thread? The code I'm trying to use is

GL.Clear(ClearBufferMask.ColorBufferBit);
GL.ClearColor(Color.Black);

GL.Begin(PrimitiveType.Quads);

GL.Color3(Color.FromArgb(255, 0, 0));
GL.Vertex2(-1, 1);
GL.Color3(Color.FromArgb(0, 255, 0));
GL.Vertex2(1, 1);
GL.Color3(Color.FromArgb(0, 0, 255));
GL.Vertex2(1, -1);
GL.Color3(Color.FromArgb(0, 255, 255));
GL.Vertex2(-1, -1f);

GL.End();
SwapBuffers();

The code above works in the same thread the GameWindow was created in but not when called from another thread.


Solution

  • I was able to swap the thread OpenGL accepts with this code

    thread = new Thread(() =>
    {
        IGraphicsContext context = new GraphicsContext(GraphicsMode.Default, window.WindowInfo);
        context.MakeCurrent(window.WindowInfo);
        //Render code here
    }).Start();