文本框的定时器/刷新功能

J.C*_*ris 1 c# multithreading refresh timer winforms

在我的应用程序中,我有两个文本框,附有两个标签:"已连接"和"未连接".如我的代码所示,如​​果建立了连接,"已连接"文本框将填充绿色,表示网络连接.如果不是,它会变红.

连接检测的功能正常工作,但是,我必须重新打开应用程序才能检测到更改.我正在寻找一种方法来自动刷新应用程序每5-10秒左右自动检测连接的任何变化.我不想清除任何其他字段或框的内容,只是清除颜色文本框.可以说是软轮询循环.我将如何使用Timer方法执行此操作.我应该创建一个新的线程来运行计时器并刷新盒子吗?

谢谢.

  if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == false)
        {
            noConnect.Select();  //if not connected, turn box red
            noConnect.BackColor = Color.Red;

        }

        else
        {
            netConnect.Select();  // if connected, turn box green
            netConnect.BackColor = Color.Lime;

        }

        //need to refresh box/application without losing other box/field contents 
        //in order to constantly check connectivity around 5-10 seconds or so
        //constantly check connectivity 
Run Code Online (Sandbox Code Playgroud)

par*_*mar 6

像这样的东西会起作用

    public Form1()
    {
        InitializeComponent();
        var timer = new Timer();
        timer.Tick += new EventHandler(timer_Tick);
        timer.Interval = 10000; //10 seconds
        timer.Start();
    }

    void timer_Tick(object sender, EventArgs e)
    {
        if (your_function_call())
        {
            netConnect.BackColor = Color.Green;
        }
        else
            netConnect.BackColor = Color.Red;
    }
Run Code Online (Sandbox Code Playgroud)

每隔一段时间就会重复调用timer_Tick,您可以轮询状态并更新控件.因为在UI线程中调用了计时器回调,所以可以更新任何UI元素.

计时器类

Timer用于以用户定义的间隔引发事件.此Windows计时器专为使用UI线程执行处理的单线程环境而设计.它要求用户代码具有可用的UI消息泵,并且始终在同一线程中操作,或者将调用编组到另一个线程上.使用此计时器时,请使用Tick事件执行轮询操作或在指定的时间段内显示闪屏.只要Enabled属性设置为true且Interval属性大于零,就会根据Interval属性设置按间隔引发Tick事件.

此解决方案使用System.Windows.Forms.Timer它调用UI线程上的tick.如果使用System.Timers.Timer回调将不在UI线程上.