Matthew Sainsbury
Matthew Sainsbury

Reputation: 1488

Starting a GameWindow in a thread

I'm trying to write an OpenTK application where you can type commands in a console window, and have a GameWindow display the result of commands.

My code looks like this:

public Program : GameWindow
{
    static void Main(string[] args)
    {
        var display = new Program();
        var task = new Task(() => display.Run());
        task.Start();

        while (true)
        {
            Console.Write("> ");
            var response = Console.ReadLine();
            //communicate with the display object asynchronously
         }
    }
}

However, the display window does not appear when started in a task or thread.

Why is this the case? I need the Run method to happen in a thread, because it is blocking for the life of the window.

Upvotes: 1

Views: 626

Answers (1)

Evk
Evk

Reputation: 101573

To fix your particular problem, just create instance of your window ("display" in your case) on thread itself:

public class Program : GameWindow {
    private static void Main(string[] args) {
        Program display = null;
        var task = new Thread(() => {
            display = new Program();
            display.Run();
        });
        task.Start();
        while (display == null)
            Thread.Yield(); // wait a bit for another thread to init variable if necessary

        while (true)
        {
            Console.Write("> ");
            var response = Console.ReadLine();
            //communicate with the display object asynchronously
            display.Title = response;
        }
    }
}

Upvotes: 2

Related Questions