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

Asked

Viewed 495 times

2

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

For some reason the tick stops running after a while (because it doesn’t 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);
    }
}
  • Just out of curiosity, if you wear one System.Threading.Timer does not give the same effect? In this case it would already do in another thread until.

  • It comes to run a few times or hangs on the first?

  • Sets "stop executing". Runs once to the end and then no longer runs? Encrava (deadlock) on first run? On what line? If you remove await Task.Run the problem disappears? What makes the method processo()? This question needs more details.

  • Every 1 second, the tick "writes" the date and time in a listview (in the example I put on the console to illustrate). If I leave the program open for a while (indeterminate) the time is not changing in listview. As to using Threading.Timer, I don’t know. I can search. I need the timer to run only when the "process" method is finished. That’s why I put a "start"/"stop" there. So it doesn’t overlap the executions.

1 answer

3


I understand what you’re trying to do, but the System.Windows.Forms.Timer was simply not created for this. This quote, direct 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 an accuracy of 55 milliseconds. If you need a multi-threaded timer with greater precision, use the Class Timer in the System.Timers namespace.

In that case, I suggest you use the System.Timers.Timer, it is possible to use it both in Winforms and any other time.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.