A
A
AramBaram2021-10-05 22:26:17
C++ / C#
AramBaram, 2021-10-05 22:26:17

How to make a timer after which the code will run?

How to make a timer in c# after which the code will run? winforms .net application

Answer the question

In order to leave comments, you need to log in

3 answer(s)
B
BasiC2k, 2021-10-05
@BasiC2k

There are two ways:
1. Programmatically
2. By placing a Timer control on the form

V
Vasily Bannikov, 2021-10-05
@vabka

For example, via Task.Delay:

async void DoSomethingDelayed() {
    await Task.Delay(TimeSpan.FromSeconds(5));
    SomethingImportant();
}

The DoSomethingDelayed method must be called at the moment from which the delay should be measured.

B
Boris the Animal, 2021-10-05
@Casper-SC

using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace WinFormsApp
{
    public partial class MainForm : Form
    {
        private readonly Timer _timer;
        private int _counter;

        public MainForm()
        {
            InitializeComponent();

            _timer = new Timer();
            _timer.Interval = 500;
            _timer.Tick += OnTimerTick;
        }

        private void OnFormLoad(object sender, EventArgs e)
        {
            _timer.Start();
        }

        private void OnTimerTick(object sender, EventArgs e)
        {
            _label.Text = $"{nameof(OnTimerTick)}. {(++_counter).ToString()}";
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question