每 X 秒执行一次指定的函数 [英] Execute specified function every X seconds

查看:28
本文介绍了每 X 秒执行一次指定的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 C# 编写的 Windows 窗体应用程序.以下函数检查打印机是否在线:

I have a Windows Forms application written in C#. The following function checks whenever printer is online or not:

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

并在打印机离线时更新图像.现在,我怎样才能每 2 秒执行一次这个函数 isonline() 这样当我拔掉打印机时,表单上显示的图像 (pictureBox1) 会变成另一个图像而无需重新启动应用程序或进行手动检查?(例如,按下运行 isonline() 函数的刷新"按钮)

and updates the image if the printer is offline. Now, how can I execute this function isonline() every 2 seconds so when I unplug the printer, the image displayed on the form (pictureBox1) turns into another one without relaunching the application or doing a manual check? (eg. by pressing "Refresh" button which runs the isonline() function)

推荐答案

使用 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();
}

您可以在Form1_Load()中调用InitTimer().

这篇关于每 X 秒执行一次指定的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆