-1

I need to wait 2 seconds for a serial port to respond, then return a value. What is the best way to accomplish that without locking the UI thread?

I have a class called Test and I create an instance of it in the main form of my program. I have several event handlers to pass data back to the main form and update the UI. My Test class has a method called runTest that has two loops. The first loop calls conTest. When that is done the second runs and calls hiPotTest. In conTest and HiPotTest I send the command via serial port to start the test. What I want to do is wait 2 seconds (for example) and get the result and return that from conTest and hiPotTest. My first thought was thread.sleep but then I decided that that would probably lock the UI during that time. Is that correct and if so what's the best way to avoid this.

I can't test this part of my program until monday at work. So right now I just have a guess as to what will happen.

4

1 回答 1

4

Having proccess go to sleep for a few seconds should be setting alarm bells off that something is wrong. While it might work now this is the type of code that will cause prod issues down then line. What if the result isn't there after 2 seconds. You'd be better off having your thread notified when the result arrives, and you have the benifit that the UI can respond straight away if the result arrives < 2 seconds.

Having said that if you really want to do it you can spwan a background thread/ timer (system.timers.timer) and have your method sleep on that. But please don't :)

于 2013-03-30T01:49:59.243 回答