Sign in to follow this  
Winegums

C#, escaping the constructor

Recommended Posts

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?)

Share this post


Link to post
Share on other sites
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. :)

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this