如何使用定时器代替 while 循环?

发布于 2025-01-04 15:55:32 字数 581 浏览 0 评论 0原文

目前我正在使用 while (true) 循环来执行此操作。我对定时器不是很熟悉。有人可以告诉我如何将其转换为与计时器一起使用吗?

string lyricspath = @"c:\lyrics.txt";
TextReader reader = new StreamReader(lyricspath);
int start = 0;
string[] read = File.ReadAllLines(lyricspath);
string join = String.Join(" ", read);
int number = join.Length;
while (true)
{
    Application.DoEvents();
    Thread.Sleep(200);
    start++;
    string str = join.Substring(start, 15);
    byte[] bytes = Encoding.BigEndianUnicode.GetBytes(str);
    label9.Text = str;
    if (start == number - 15)
    {
        start = 0;
    }
}

at the moment i am using a while (true) loop to do this. I am not very familiar with timers. can someone tell me how i would convert this to work with a timer?

string lyricspath = @"c:\lyrics.txt";
TextReader reader = new StreamReader(lyricspath);
int start = 0;
string[] read = File.ReadAllLines(lyricspath);
string join = String.Join(" ", read);
int number = join.Length;
while (true)
{
    Application.DoEvents();
    Thread.Sleep(200);
    start++;
    string str = join.Substring(start, 15);
    byte[] bytes = Encoding.BigEndianUnicode.GetBytes(str);
    label9.Text = str;
    if (start == number - 15)
    {
        start = 0;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

彼岸花似海 2025-01-11 15:55:32

为什么要使用定时器?我认为这是因为您希望应用程序在如此漫长的操作过程中保持响应。如果是这样,请考虑使用相同类型的代码,但在后台工作程序中。

另外,如果您确实想使用计时器,请注意您使用的是哪一个; Systm.Timer 在与应用程序热窗体使用的线程不同的线程中调用其事件。表单线程中的表单事件中的计时器。您可能需要在计时器回调中调用 Invoke() 更改标签的操作。

Why use a timer? I assume this is because you want to have the app remain responsive during such a supposedly long operation. If so cosider using the same sort of code but in a BackgroundWorker.

Also if you do specifically want to use a Timer, beware which one you use; the Systm.Timer invokes its event in a different thread to the one used by the applications hoting form. The Timer in Forms events in the forms thread. You may need to Invoke() the operations in a timer callback that change the label.

秋千易 2025-01-11 15:55:32

基本上,计时器只是坐在那里计数,每 X 毫秒它就会“滴答”一声;它会引发一个事件,您可以使用一种方法订阅该事件,该方法每 X 毫秒执行您想要执行的操作。

首先,循环内部需要的所有来自循环外部的变量都需要具有“实例范围”;它们必须是当前具有此方法的对象的一部分,而不是像现在这样的“局部”变量。

然后,您当前的方法将需要执行 while 循环之前的所有步骤,设置我提到的“实例”变量,然后创建并启动一个计时器。 .NET中有多种定时器;最有用的两个可能是 System.Windows.Forms.Timer 或 System.Threading.Timer。需要为该计时器提供一个在“滴答”时应调用的方法的句柄,并且应告知其“滴答”的频率。

最后,while 循环内的所有代码(除了对 Application.DoEvents() 和 Thread.Sleep() 的调用之外)都应放置在计时器“滴答”时运行的方法中。

像这样的东西应该有效:

private string[] join;
private int number;
private int start;
private Timer lyricsTimer;

private void StartShowingLyrics()
{
   string lyricspath = @"c:\lyrics.txt";
   TextReader reader = new StreamReader(lyricspath);
   start = 0;
   string[] read = File.ReadAllLines(lyricspath);
   join = String.Join(" ", read);
   number = join.Length;

   lyricsTimer = new System.Windows.Forms.Timer();
   lyricsTimer.Tick += ShowSingleLine;
   lyricsTimer.Interval = 300;
   lyricsTimer.Enabled = true;
}


private void ShowSingleLine(object sender, EventArgs args)
{
    start++;
    string str = join.Substring(start, 15);
    byte[] bytes = Encoding.BigEndianUnicode.GetBytes(str);
    label9.Text = str;
    if (start == number - 15)
    {
        start = 0;
    }
}

Basically, a timer just sits there and counts, and every X milliseconds it "ticks"; it raises an event, which you can subscribe to with a method that does whatever you want done every X milliseconds.

First, all of the variables you will need inside the loop, that come from outside the loop, will need to have "instance scope"; they must be a part of the object that currently has this method, and not "local" variables like they are now.

Then, your current method will need to perform all of the steps prior to the while loop, setting whose "instance" variables I mentioned, and then create and start a Timer. There are several Timers in .NET; the two that would be most useful would likely be either the System.Windows.Forms.Timer or the System.Threading.Timer. This timer will need to be given a handle to the method it should call when it "ticks", and should be told how often to "tick".

Finally, all the code inside the while loop, EXCEPT the calls to Application.DoEvents() and Thread.Sleep(), should be placed in the method that the Timer will run when it "ticks".

Something like this ought to work:

private string[] join;
private int number;
private int start;
private Timer lyricsTimer;

private void StartShowingLyrics()
{
   string lyricspath = @"c:\lyrics.txt";
   TextReader reader = new StreamReader(lyricspath);
   start = 0;
   string[] read = File.ReadAllLines(lyricspath);
   join = String.Join(" ", read);
   number = join.Length;

   lyricsTimer = new System.Windows.Forms.Timer();
   lyricsTimer.Tick += ShowSingleLine;
   lyricsTimer.Interval = 300;
   lyricsTimer.Enabled = true;
}


private void ShowSingleLine(object sender, EventArgs args)
{
    start++;
    string str = join.Substring(start, 15);
    byte[] bytes = Encoding.BigEndianUnicode.GetBytes(str);
    label9.Text = str;
    if (start == number - 15)
    {
        start = 0;
    }
}
冰火雁神 2025-01-11 15:55:32

每 200 毫秒运行一次。但在这里提问之前先尝试谷歌的建议是一个很好的建议。

using Timer = System.Windows.Forms.Timer;

private static readonly Timer MyTimer = new Timer();
...
MyTimer.Tick += MyTimerTask;
MyTimer.Interval = 200; // ms
MyTimer.Enabled = true;
...
private void MyTimerTask(Object o, EventArgs ea)
{
    ...
}

This runs every 200 ms. But the suggestion to try Google before asking a question here is a good one.

using Timer = System.Windows.Forms.Timer;

private static readonly Timer MyTimer = new Timer();
...
MyTimer.Tick += MyTimerTask;
MyTimer.Interval = 200; // ms
MyTimer.Enabled = true;
...
private void MyTimerTask(Object o, EventArgs ea)
{
    ...
}
夢归不見 2025-01-11 15:55:32

只需定义一个新计时器:

        Timer timer1 = new Timer();
        timer1.Interval = 1; // Change it to any interval you need.
        timer1.Tick += new System.EventHandler(this.timer1_Tick);
        timer1.Start();

然后定义一个将在每个计时器滴答声(每 [Interval] 毫秒)中调用的方法:

    private void timer1_Tick(object sender, EventArgs e)
    {
        Application.DoEvents();
        Thread.Sleep(200);
        start++;
        string str = join.Substring(start, 15);
        byte[] bytes = Encoding.BigEndianUnicode.GetBytes(str);
        label9.Text = str;
        if (start == number - 15)
        {
            start = 0;
        }
    }

*请记住在方法外部定义变量,以便您能够在timer1_Tick 方法中访问它们.

Simply define a new timer:

        Timer timer1 = new Timer();
        timer1.Interval = 1; // Change it to any interval you need.
        timer1.Tick += new System.EventHandler(this.timer1_Tick);
        timer1.Start();

Then define a method that will be called in every timer tick (every [Interval] miliseconds):

    private void timer1_Tick(object sender, EventArgs e)
    {
        Application.DoEvents();
        Thread.Sleep(200);
        start++;
        string str = join.Substring(start, 15);
        byte[] bytes = Encoding.BigEndianUnicode.GetBytes(str);
        label9.Text = str;
        if (start == number - 15)
        {
            start = 0;
        }
    }

*Remember to define the variables outside the method so you will be able to access them in the timer1_Tick method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文