我如何创建计时器循环,以便每隔一秒滴答就执行相同的功能 [英] How do i create timer loop so that every tick seconds the same function is performed

查看:143
本文介绍了我如何创建计时器循环,以便每隔一秒滴答就执行相同的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我有:

hello, i have:

private void scrollup_Click(object sender, EventArgs e)
        {
            t.Enabled = false;
            while (t.Enabled == false)
            {
                scroll(telep.Handle, (speedslider.Value * 2));
            }
        }




其中t是我的计时器. scroll(telep.Handle, (speedslider.Value * 2));是非常长且无聊的功能的缩写,它用滚动条的值乘以两(2)来滚动滚动条.
使用while (t.Enabled == true)并不是很好,因为如果我尝试在滚动时与表单进行交互,则表单会在几秒钟内变得无响应,然后一直滚动到底部.

我当时在考虑使用计时器来滚动2个像素,比如说30毫秒,但是我对计时器知之甚少.

如果有人可以将我带入正确的方向,或者甚至完全告诉我该怎么做,那将很棒.




where t is my timer. scroll(telep.Handle, (speedslider.Value * 2)); is short for a very very long and boring function, that pretty much scrolls the scrollbar by the value of a track bar multiplied by two (2).
Using while (t.Enabled == true) is not very good because if I try to interact with the form while it is scrolling, the form becomes unresponsive for a sec, then is scrolled all the way to the bottom.

I was thinking of using a timer for scrolling 2 pixels every, lets say for e.g., 30 milliseconds, but I do not know much about timers.

If someone could throw me into the correct direction, or even completely tell me how to do this, that would be great.

thanks to all who answer.

推荐答案

即使您使用计时器,如果它每30毫秒触发一次,并且您在处理程序中有UI代码,那么您的UI仍然几乎没有任何反应.您需要以不同的方式查看此操作,也许是通过后台线程.

[更新]
~~~~~~~~~

实际上,您可以使用辅助线程和Sleep.这样的事情会做你想要的.您将看到平滑的滚动,并且您的UI应保持响应状态:

Even if you use a timer, if it''s fired every 30ms and you have UI code in the handler, then your UI will still be mostly unresponsive. You need to look at doing this in a different way, perhaps via a background thread.

[Update]
~~~~~~~~~

Actually you could use a worker thread and Sleep. Something like this will do what you want. You will see a smooth scrolling, and your UI should remain responsive:

private void ScrollButton_Click(object sender, EventArgs e)
{
    var worker = new BackgroundWorker();
    worker.DoWork += ScrollWorker_DoWork;
    worker.RunWorkerAsync();
}

void ScrollWorker_DoWork(object sender, DoWorkEventArgs e)
{
    for (int value = 0; value < someValue; value++)
    {
        scroll(value);
        Thread.Sleep(30); // experiment with this, try 60, 90, etc.
    }
}


MSDN上的页面 [
The page on MSDN[^] shows how to use the Tick event of the timer, which is the normal way to do this sort of thing. You control the periodicity by using the Interval property, for your 30 milliseconds, set it to 30 but be sure that your scroll method completes within this time period.


这篇关于我如何创建计时器循环,以便每隔一秒滴答就执行相同的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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