C#, escaping the constructor

Started by
2 comments, last by Captain P 16 years, 11 months ago
While trying to write C# apps, i've noticed that example code i've seen all seems to work from a constructor, and never escape it (once it hits the end of the constructor, it's done). I haven't found an example of an application that runs the constructor then goes on to perform other tasks. Since the application I want to write involves looping indefinatley, I'm kinda stuck here. from what i understand, Application.Run(new constructor()) creates a new class instance and calls the constructor, fine. But how do I then run other functions from the class? Do I also call them in Main (effectivley, do I treat Main as a Setup() function?)
Advertisement
I struggled with the same issue a few days ago. However, you worded it incorrectly: it's not the constructor that you're 'stuck' at, it's the run function. The Window gets constructed, and is passed into the run function. It'll then take control, handle events when they occur, and basically, leave you with an event-diven system.

What I did was creating a separate thread and start my own main loop from there, before calling that run function. In this new thread, you can do whatever you want, but keep in mind that you're working with multiple threads now, so calling functions on your Window might cause problems. I haven't yet investigated how to do it in a safe way, but that takes a little work. There's some info on MSDN on that and tutorials on creating threads in C# shouldn't be hard to find.

I hope that helps. :)
Create-ivity - a game development blog Mouseover for more information.
Depending on what you are doing, you should probably be using the Application.Idle event, which is fired every time there are no messages in the queue left to be processed. That is assuming you are writing a game.

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

Thanks for the suggestion, Washu. However, when I tried updating the logic and screen from within the Idle callback function, I found that it's only being processed once after the incoming events have been handled, so it's of no use for continuously updating something. I've also tried updating things from within a repaint callback, and refreshing the window from there, which essentially creates a loop, but that gives a lot of screen flickering and an unresponsive window.
Create-ivity - a game development blog Mouseover for more information.

This topic is closed to new replies.

Advertisement