Reputation: 11
I am a beginner in c#, and I couldn't find out how to make a simple function run all the time in winform. I want to run a function simultaneously with the main code, so that it can lower a stat all the time. how can I do that?(Sorry if this question already exists, I did search it and came up with nothing). g.p.
Upvotes: 1
Views: 835
Reputation: 13177
The closest way you can get to running a method "all the time" is by running a while(true)
loop in a thread. However, this will start to take CPU resources, and assuming you also want to interact with the form in the method, you would have to invoke the main thread all the time, which will also lag your application.
The second way is to add a Timer component to the form. You can set the interval of the timer, and specify the method to be called when the timer ticks. The method will be run on the main thread, so accessing other controls is as easy as possible. However, don't run CPU-intensive task in the method, as will also lag the application.
You can also use async
and await
to run a while(true)
loop once and use await Task.Delay(delay);
to pause it for a small time, but this is not as efficient as using the timer.
Another option close to running a method all the time is using the event Application.Idle
. It will run the method only when all window messages are processed, and therefore won't lag the form (assuming your method is fast enough). On the other hand, you aren't guaranteed the method will be running with a constant rate.
If you are creating a game with a main loop, using Winforms is really not an optimal way to do it. You can try XNA. Otherwise, just use a timer with a reasonably small delay.
Upvotes: 4