C# Best Way to Run a Function Every Second, Timer VS Thread

C# Best Way to run a function every second, Timer vs Thread?

I'd use a System.Threading.Timer because it generally uses less resources than a devoted thread. Here's an example:

using System;
using System.Threading;

namespace Demo
{
public static class Program
{
public static void Main()
{
Console.WriteLine("Starting timer with callback every 1 second.");

Timer timer = new Timer(callback, "Some state", TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));

Thread.Sleep(4500); // Wait a bit over 4 seconds.

Console.WriteLine("Changing timer to callback every 2 seconds.");

timer.Change(TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(2));

Thread.Sleep(9000);

timer.Change(-1, -1); // Stop the timer from running.

Console.WriteLine("Done. Press ENTER");

Console.ReadLine();
}

private static void callback(object state)
{
Console.WriteLine("Called back with state = " + state);
}
}
}

This is a good choice for a Console app. However, you must of course bear in mind that the callback is still being done on a separate thread from the main thread, so you must be careful about synchronising resources and variables shared between the callback and the main thread.

Which is the best way to call multiple method repeatedly in c# timer or thread?

In both cases, Thread or Timer, your methods will just be executed in different threads, in parallel with other threads.

The main difference is this:

  • Thread will use a dedicated thread for the task
  • Timer will use a thread taken from Thread Pool and the thread will be used for the task only when the method runs. Between one interval and the next one the same thread could be used by someone else.

Therefore all comes down to your use case: if your application uses a lot of threads Timer can be more efficient. If the method you are invoking takes a lot of time, there would be no benefits to use Timer instead of Thread as the thread would not be recycled.

Which is the best practice to call a method every x seconds?

Interface: I recommend you create something like startPoll() and endPoll() inside your controller class: This is the only place, where all necessary information to avoid multiple-call, interleaving etc. are in scope.

Implementation: I recommend spinning off a dedicated thread: The thread pool and other built-in mechanisms are not designed for work, that has a high degree of independance from the rest of the app (such as communicating with other hardware). This thread could be started by startPoll() and signalled to end by endPoll().

Timer: I definitly do NOT recommend using a timer - you go straight into parallel-call-hell, if one check takes longer than the wait for the next check (or you need plumbing code to avoid that). I recommend you calculate the ealiest next start time before you start your work cycle, then when finished WaitOne() on the stop signal for the remaining time.

Execute specified function every X seconds

Use System.Windows.Forms.Timer.

private Timer timer1; 
public void InitTimer()
{
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 2000; // in miliseconds
timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
isonline();
}

You can call InitTimer() in Form1_Load().

Best way to create a "run-once" time delayed function in C#

I don't know which version of C# you are using. But I think you could accomplish this by using the Task library. It would then look something like that.

public class PauseAndExecuter
{
public async Task Execute(Action action, int timeoutInMilliseconds)
{
await Task.Delay(timeoutInMilliseconds);
action();
}
}

Run function every 10 seconds

follow this :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void addFirstSlide()
{
PowerPoint.Slide firstSlide = Globals.ThisAddIn.Application.ActivePresentation.Slides[1];
PowerPoint.Shape textBox2 = firstSlide.Shapes.AddTextbox(
Office.MsoTextOrientation.msoTextOrientationHorizontal, 50, 50, 500, 500);
textBox2.TextFrame.TextRange.InsertAfter("firstSlide");
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval = 1000;
timer1.Enabled = true;
}

private void timer1_Tick(object sender, EventArgs e)
{
addFirstSlide();
}
}
}


Related Topics



Leave a reply



Submit