Button Click to stop a test

三世轮回 提交于 2021-01-29 04:41:46

问题


I have a Test Engine that executes multiple tests, until all tests have been executed.

Each test object has an Execute and Resume method. These methods return a status:

  • Waiting for reply from COM port
  • Waiting for button click from User
  • Testing completed.

In the GUI, the User starts the Test Engine by clicking a button. In other words, the click event for the button calls the Test Engine's start method.

Next, a test may send a message through the COM port and must suspend until a message is received from the COM port. I have the COM port interrupt process the message, then call the Test Engine's resume method.

A test may need information from the user. In this case, the test displays a message in a text box, then returns. A click event handler of a button will call the Test Engine's resume method.

This works fine, except now I need to have a test repeatedly send message through the COM port and receive reply. This loop will only be terminated by a click from a button on the GUI.

I have learned that the COM port interrupt handler runs in a different thread than the GUI. The tests execute GUI methods by using a delegate.

How can I have the Test Engine check for button click while also waiting for a COM port message? The Test Engine should check for button click after receiving a COM port message in order to keep the message system synchronized.

Notes:
I was thinking about having the Test Engine run in a worker thread, with semaphores for message received from COM port and another semaphore for the stop button. The Test Engine would pend on the message semaphore, wake up, process the message, then check the stop button semaphore.

Using C# with Visual 2010 Express on Windows 7.


回答1:


I think the BackgroundWorker component might be able to help you with this. It's designed to take some code and run it in a background thread, with an easy method for cancellation (the button calls CancelAsync(), and your test engine would check the CancellationPending property to see if it needs to cancel).

What you'd do is add one to your form. Then you wrap up your COM port testing code in a method, which you hook up to the worker's DoWork event handler.

When you want to start working, call runWorkerAsync(). That worker code after testing the COM port should check the CancellationPending property, and return if it's true. As I mentioned, your button event handler for cancellation calls CancelAsync() to set that property.

BackgroundWorker also supports an event for showing progress, but you don't have to hook that up if you don't want to use.



来源:https://stackoverflow.com/questions/4750984/button-click-to-stop-a-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!