开发者

How to change String value after 5 sec?

I'm willing to write program that after 5 sec shows text that was hidden and after another 5 sec changes both. Example: - program start: TEXT 1 - after 5 sec: TEXT 1 TEXT 2 - after 5 sec: TEXT 3 - after 5 sec: TEXT 3 TEXT 4 ...

开发者_Python百科

How I can in C# count those seconds?


You can use a timer.


There are three Timer classes in .NET (that I know of and have used). If you are writing a Windows Forms application, the simplest thing would be to add a System.Windows.Forms.Timer and create an event handler for its Tick event. (Note that the interval is measured in milliseconds, so you would set it to 5000 for 5 seconds.) The other timers work similarly.

Below is an example of how you could use a System.Threading.Timer with a lambda expression for the callback function (in which you would change the text mentioned in your question). (Note that you will need to marshal the call back to the GUI thread if you are updating a Control on a GUI. This would be accomplished by using Form.Invoke() after checking Form.InvokeRequired.)

var timer = new System.Threading.Timer(
    (object state)=>{ /* Your logic here */ },
    null,
    0,
    5000);
...
timer.Dispose(); // Don't forget to Dispose of the Timer when your app closes


Please see EggTimer in C# for a good example:

This simple timer app will count down from whatever value is set in the textbox.


There are a variety of options. System.Threading.Sleep allows you to block for a particular amount of time. System.Threading.WaitHandle subclasses do as well, and you can interrupt the sleep if you need to. Finally Timer can be used. In all cases make sure you get your synchronization right.


Try using a Timer.


If your view doesn't have to be responsive during that first 5 seconds you put the UI thread to sleep and change it afterwards. This way you can avoid passing the functionality back to the UI thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜