每隔X秒执行指定的功能

Dev*_*oot 53 .net c# winforms

我有一个用C#编写的Windows窗体应用程序.无论何时打印机在线,以下功能都会检查:

public void isonline()
{
    PrinterSettings settings = new PrinterSettings();
    if (CheckPrinter(settings.PrinterName) == "offline")
    {
        pictureBox1.Image = pictureBox1.ErrorImage;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果打印机处于脱机状态,则更新映像.现在,我怎么能isonline()每2秒执行一次这个功能,所以当我拔下打印机时,表格(pictureBox1)上显示的图像变成另一个,而不重新启动应用程序或进行手动检查?(例如,按下运行该isonline()功能的"刷新"按钮)

Ste*_*cya 101

使用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();
}
Run Code Online (Sandbox Code Playgroud)

你可以调用InitTimer()Form1_Load().

  • "Timer"对象现在似乎有不同的配置.我用它来工作:`timer = new Timer(TimerCallback,null,0,timeStepInMilliseconds)`+`private static void TimerCallback(Object stateInfo)`. (7认同)

Dae*_*ire 24

.NET 6 添加了该类PeriodicTimer

var periodicTimer= new PeriodicTimer(TimeSpan.FromSeconds(1));
while (await periodicTimer.WaitForNextTickAsync())
{
    // Place function in here..
    Console.WriteLine("Printing");
}
Run Code Online (Sandbox Code Playgroud)

您可以使用以下命令在后台运行它:

async Task RunInBackground(TimeSpan timeSpan, Action action)
{
    var periodicTimer = new PeriodicTimer(timeSpan);
    while (await periodicTimer.WaitForNextTickAsync())
    {
        action();
    }
}

RunInBackground(TimeSpan.FromSeconds(1), () => Console.WriteLine("Printing"));
Run Code Online (Sandbox Code Playgroud)

PeriodicTimer与循环相比,其主要优点Timer.Delay在执行慢速任务时最容易观察到。

using System.Diagnostics;

var stopwatch = Stopwatch.StartNew();
// Uncomment to run this section
//while (true)
//{
//    await Task.Delay(1000);
//    Console.WriteLine($"Delay Time: {stopwatch.ElapsedMilliseconds}");
//    await SomeLongTask();
//}

//Delay Time: 1007
//Delay Time: 2535
//Delay Time: 4062
//Delay Time: 5584
//Delay Time: 7104

var periodicTimer = new PeriodicTimer(TimeSpan.FromMilliseconds(1000));
while (await periodicTimer.WaitForNextTickAsync())
{
    Console.WriteLine($"Periodic Time: {stopwatch.ElapsedMilliseconds}");
    await SomeLongTask();
}

//Periodic Time: 1016
//Periodic Time: 2027
//Periodic Time: 3002
//Periodic Time: 4009
//Periodic Time: 5018

async Task SomeLongTask()
{
    await Task.Delay(500);
}
Run Code Online (Sandbox Code Playgroud)

PeriodicTimer将尝试每 n * 延迟秒调用一次,而Timer.Delay将每 n * (延迟 + 方法运行时间)秒调用一次,导致执行时间逐渐不同步。


小智 7

随着时间的推移,事情发生了很大变化。您可以使用以下解决方案:

static void Main(string[] args)
{
    var timer = new Timer(Callback, null, 0, 2000);

    //Dispose the timer
    timer.Dispose();
}
static void Callback(object? state)
{
    //Your code here.
}
Run Code Online (Sandbox Code Playgroud)

  • 让我补充一点,这个计时器来自 System.Threading 命名空间。 (4认同)

phi*_*x_x 6

最适合初学者的解决方案是:

从工具箱中拖动计时器,为其指定名称,设置所需的间隔,并将"已启用"设置为True.然后双击Timer和Visual Studio(或您正在使用的任何内容)将为您编写以下代码:

private void wait_Tick(object sender, EventArgs e)
{
    refreshText(); // Add the method you want to call here.
}
Run Code Online (Sandbox Code Playgroud)

无需担心将其粘贴到错误的代码块或类似的东西中.


pau*_*011 5

螺纹:

    /// <summary>
    /// Usage: var timer = SetIntervalThread(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetIntervalThread(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be disposed.</returns>
    public static System.Threading.Timer SetIntervalThread(Action Act, int Interval)
    {
        TimerStateManager state = new TimerStateManager();
        System.Threading.Timer tmr = new System.Threading.Timer(new TimerCallback(_ => Act()), state, Interval, Interval);
        state.TimerObject = tmr;
        return tmr;
    }
Run Code Online (Sandbox Code Playgroud)

常规的

    /// <summary>
    /// Usage: var timer = SetInterval(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetInterval(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be stopped and disposed.</returns>
    public static System.Timers.Timer SetInterval(Action Act, int Interval)
    {
        System.Timers.Timer tmr = new System.Timers.Timer();
        tmr.Elapsed += (sender, args) => Act();
        tmr.AutoReset = true;
        tmr.Interval = Interval;
        tmr.Start();

        return tmr;
    }
Run Code Online (Sandbox Code Playgroud)