Task.Run locking inside a "tick" (Forms.Timer)

1

In my application, I created a "Timer" (System.Windows.Forms) that runs every 1 second. In the "tick" event, I put a await Task.Run.

For some reason the tick stops running after a while (because it does not print the date and time on the console).

Class x {
    public Timer timer {get; set;}

    public void f()
    {
        timer = new Timer();
        timer.Tick += new EventHandler(this.tick);
        timer.Enabled = false;
        timer.Interval = 1000;
        timer.Start();
    }

    private async void tick(object sender, EventArgs e)
    {
        this.status = ProcessoStatus.TRABALHANDO;
        this.timer.Stop();

        try
        {
            await Task.Run(() => this.processo());
        }
        catch
        {}

        this.timer.Start();
        this.status = ProcessoStatus.OCIOSO;
    }

    public void processo()
    {
        Console.WriteLine(DateTime.Now);
    }
}
    
asked by anonymous 01.09.2015 / 21:55

1 answer

2

I understand what you're trying to do, however, System.Windows.Forms.Timer was simply not created for this. This quote, straight from MSDN:

  The Windows Forms Timer component is single-threaded, and is limited to an accuracy of 55 milliseconds. If you require a multithreaded timer with greater accuracy, use the Timer class in the System.Timers namespace.

Or, in Portuguese:

  

The Windows Forms Timer component is single-threaded and is limited to 55 milliseconds precision. If you need a multithreaded timer with greater precision, use the Timer class in the System.Timers namespace.

In this case, I suggest that you use System.Timers.Timer , and you can use it in both WinForms and any other instant.

    
02.09.2015 / 05:17