简体   繁体   English

在线程中启动GameWindow

[英]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. 我正在尝试编写一个OpenTK应用程序,您可以在其中在控制台窗口中键入命令,并让GameWindow显示命令结果。

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. 我需要在线程中执行Run方法,因为它在窗口的生命周期内处于阻塞状态。

To fix your particular problem, just create instance of your window ("display" in your case) on thread itself: 要解决您的特定问题,只需在线程本身上创建窗口的实例(在您的情况下为“ display”):

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;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM