简体   繁体   中英

how do I implement something like JavaScript's setTimeout in C#?

I have a C# app that receives updates from a server, processes it, and updates the GUI. the updates come in constantly, say several times a second. I want the app to update the GUI at most once every 2 seconds. so if an update comes in at time T, I want all updates that come in from T through T+2sec to stay in a buffer, and at T+2sec do the processing and GUI update. I know in JS you can use setTimeout() to execute some code at some time in the future, so I want something like that.

what's an appropriate way to do this? I've heard that using threads to "schedule" a function call isn't a great idea, but I'm not sure of a better way to do this. would it be so bad to use a Timer with a two second interval, synchronized to the GUI thread, that does the processing/updating?

You can use a System.Windows.Forms.Timer . It doesn't run events in a separate thread, it's the GUI thread that runs them. That way you can update the GUI directly without having to use Invoke.

You should use one of the timer classes, as you posted in your question.

See this MSDN article comparing them - this should give you a good basis to make a decision.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM