开发者

Console CTRL-C handling when using serial port fails

Using VB.Net I'v开发者_StackOverflow中文版e added a CTRL-C handler:

 AddHandler Console.CancelKeyPress, AddressOf QuitHandler

Which does the following:

Private Sub QuitHandler(ByVal sender As Object, ByVal args As ConsoleCancelEventArgs)

        Console.WriteLine("Quitting...")
        args.Cancel = True
        Quit = True
    End Sub

I then have a main loop which just runs until Quit=True.

This all works until I start reading from the serial port:

 Private Sub port_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles Port.DataReceived

at which point the CTRL-C handler gets ignored for about 30secs at which point the console app just terminates without going through the cleanup code.

Why?


I don't know VB, but my guess would be that you're attempting to read data from the serial port that isn't there (err, the port is there, the data isn't); as a result, your program is blocking ("hanging") until the read attempt times out after 30 seconds.

If I'm correct, you need some way to poll your serial input without blocking, or (better) to get an asynchronous sub called when data actually appears.


You should make sure to understand how Timeouts work, since you are reading serial port on pooling. Your serial thread will always be running and trying to read something.

A best approuch would be to read data just when its availiable, then your serial thread would have time to breath.

You can also try to use DoEvents.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜