Function

private void MainForm_Load(object sender, EventArgs e) { timer_update.Interval = IntervalUpdate; timer_update.Tick += new EventHandler(MainForm_Load); timer_update.Enabled = true; } 

After 7-8 timer operations in the task manager does not respond and begins to eat the processor. How can you avoid this or in some other way to regularly update the function MainForm_Load?

  • 3
    Ahhhh! Recursive Bomb! All the shelter! - VladD
  • beautiful, laughed - Disa
  • What were you trying to do? - 4per
  • in the MainForm_Load function, I have to handle the program (Handling a request to the server and outputting all the necessary information). And it is necessary that the function is restarted. I understand that adding a event to tick occurs by adding + =, but this also starts to overload the program. - Disa

2 answers 2

1. "Do not confuse warm with soft"

The first and main error is that you are trying to cram all the program logic into event handlers. You do not need to do this, because if you need to slightly change the logic, you will have to go into the code of visual components, etc. etc. with all the headaches it causes.

Event handler code should be as short and simple as possible. There are usually quite a lot of events and handlers and it is easy to get confused in them. Especially if pieces of code are simply copied from the handler to the handler.

2. We separate model and representation

In the simplest case, it is enough to create a separate class or set of classes for storing and processing data. Let's call this class conditionally MyModel . In this class, define the fields for storing data and the method for loading them, for example
public void LoadData() in which you make all the necessary actions to get data. You also define properties in this class for controlled access to data and transfer them to visual components for display and, possibly, modification.

3. How does it look and how to use it?

Determine the model

 public class MyModel { public int MyData1 { get; private set; }//свойство только для чтения public string MyData2 { get; set; }//свойство для чтения и записи ... //остальные нужные свойства ... public void LoadData() { MyData1 = 100500;//замените на вашу логику получения данных MyData2 = "I'm cool string"; } ... //остальная логика работы с данными модели } 

now in shape

 public class MainForm : Form { private MyModel model;//форма должна знать что у нее есть модель, //поэтому размещаем ссылку на нашу модель private void MainForm_Load(object sender, EventArgs e) { //Инициализируем модель и загружаем данные model = new MyModel(); model.LoadData(); //Настраиваем таймер timer_update.Interval = IntervalUpdate; timer_update.Tick += new EventHandler(TickHandler); timer_update.Enabled = true; } private void TickHandler(object sender, EventArgs e) { model.LoadData(); } //далее все остальное что там нужно } 

Already noticed the difference? Even if you need to change the logic of data loading, you will do it in one single place and not suffer from copy-paste errors. If you need to change the visual components - this, again, will not affect the model.

The example is greatly simplified, and far from ideal, although it is quite suitable for an application with one main form. Read more in the literature on design patterns (disign patterns), for example, here to start. As applied to WinForms, MVP (Model-View-Presenter) or MVPVM is the closest, but the latter is more complex and there is not always a real need, but I recommend to get acquainted with all the patterns and anti-patterns in order to have a basic idea of how, when and why they are applied, even if you don’t figure it out right away - it’s not scary, understanding will come with time and experience, well, or ask another question here =)

    You do not need to use the MainForm_Load method as a handler for the Tick event, after each tick this method will be called and create a new subscriber for the Tick event - again the MainForm_Load method. This causes endless recursion and unlimited addition of handlers to the Tick event — after the first Tick, the number of handlers is 2, after the second, 4, etc. until the memory runs out. You need to create a method that must be run on each Tick, in this method there should not be a Tick event subscriber. For example, your code can be changed as follows:

     `//Этот метод должен вызываться один раз! чтобы не создавать ненужных подписчиков на событие Tick private void MainForm_Load(object sender, EventArgs e) { timer_update.Interval = IntervalUpdate; timer_update.Tick += new EventHandler(TickHandler); //здесь TickHandler, а не MainForm_Load timer_update.Enabled = true; } private void TickHandler(object sender, EventArgs e) { //Логика по обработке события Tick }` 
    • but in this case, nothing will happen on the first boot until the timer starts running. And if I set the timer to 300 seconds, then the first five minutes will fail. - Disa
    • one
      at the first boot, if necessary, you can simply call the TickHandler method. - Oleg Kulaev
    • Or, when creating a Timer, you can specify an initial delay - 0, then the Tick handler will be called immediately after the timer starts, the parameter is called dueTime in the Timer constructor - Oleg Kulaev
    • But is it possible? LoadProgramm (sender, e); timer_update.Interval = IntervalUpdate; timer_update.Tick + = new EventHandler (LoadProgramm); timer_update. Enabled = true; - Disa