Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. .NET (Core and Framework)
  4. Clean way to have an abortable read for serial or TCP stream?

Clean way to have an abortable read for serial or TCP stream?

Scheduled Pinned Locked Moved .NET (Core and Framework)
businesstutorialquestionannouncementlearning
5 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    supercat9
    wrote on last edited by
    #1

    In my application (VBexpress 2005), I would like to have a process read data from an incoming stream and process it. A blocking read would be fine except that I would like the user to be able to switch between serial ports and TCP connections. It would not be acceptable to simply leave the unused connections open--system requirements dictate that they actually be closed. Which of the following approaches would be best:

    1. Use a blocking read with a timeout, and figure out some method to get rid of all the 'first chance exception' messages for the timeouts (can anyone tell me how to do that without having to globally disable all first-chance messages)? This would involve some waste of CPU time, but if I use a one-second timeout it wouldn't be too bad; delaying the release of the resource by a second would not be objectionable.
    2. Use a blocking read, and then use .Interrupt on the thread if the port needs to be closed. I'm not sure whether that's guaranteed to work without problems, however.
    3. Use a blocking read, and then rudely close the port in another thread. I think that would probably "usually" cause the read to immediately return a failure, but I don't know that such behavior would be guaranteed.
    4. Use a non-blocking read and close the port while it's pending. I'm not sure whether that would be "safe" either.
    5. Somehow do a read which will wait up to an indicated amount of time (without busy-waiting), but--if no data arrives--will simply return no data rather than throwing an exception. I think I can do this with the TCP ports, but don't see how to do it with serial ports other than busy-waiting.
    6. Something else?

    If there were a documented way of telling the system to abandon an asynchronous read operation, that would probably be the ideal method. Unfortunately, I know of no way to do that. I don't want to simply experiment and go with whatever works, because--other than the timeout method--all the approaches rely upon partial thread safety of operations which are not specified as thread-safe. The timeout method is in some ways a little icky, but I'd actually prefer to go with that for simplicity if I could get rid of the annoying "First chance exception" messages. Is there any nice way to do that?

    modified on Thursday, January 8, 2009 2:55 PM

    M 1 Reply Last reply
    0
    • S supercat9

      In my application (VBexpress 2005), I would like to have a process read data from an incoming stream and process it. A blocking read would be fine except that I would like the user to be able to switch between serial ports and TCP connections. It would not be acceptable to simply leave the unused connections open--system requirements dictate that they actually be closed. Which of the following approaches would be best:

      1. Use a blocking read with a timeout, and figure out some method to get rid of all the 'first chance exception' messages for the timeouts (can anyone tell me how to do that without having to globally disable all first-chance messages)? This would involve some waste of CPU time, but if I use a one-second timeout it wouldn't be too bad; delaying the release of the resource by a second would not be objectionable.
      2. Use a blocking read, and then use .Interrupt on the thread if the port needs to be closed. I'm not sure whether that's guaranteed to work without problems, however.
      3. Use a blocking read, and then rudely close the port in another thread. I think that would probably "usually" cause the read to immediately return a failure, but I don't know that such behavior would be guaranteed.
      4. Use a non-blocking read and close the port while it's pending. I'm not sure whether that would be "safe" either.
      5. Somehow do a read which will wait up to an indicated amount of time (without busy-waiting), but--if no data arrives--will simply return no data rather than throwing an exception. I think I can do this with the TCP ports, but don't see how to do it with serial ports other than busy-waiting.
      6. Something else?

      If there were a documented way of telling the system to abandon an asynchronous read operation, that would probably be the ideal method. Unfortunately, I know of no way to do that. I don't want to simply experiment and go with whatever works, because--other than the timeout method--all the approaches rely upon partial thread safety of operations which are not specified as thread-safe. The timeout method is in some ways a little icky, but I'd actually prefer to go with that for simplicity if I could get rid of the annoying "First chance exception" messages. Is there any nice way to do that?

      modified on Thursday, January 8, 2009 2:55 PM

      M Offline
      M Offline
      Mark Churchill
      wrote on last edited by
      #2

      You'll pretty much have to read with timeout. The blocking reads will block in unmanaged code... which prevents things like thread.abort. I normally have "break on thrown" on, and then disable that for all the exceptions that I can't work around. Current app I'm working on is a very large SCADA app - and the only "expected" exceptions come from an SVG library that doesn't have a "TryGetElement" :S

      Mark Churchill Director, Dunn & Churchill Pty Ltd Free Download: Diamond Binding: The simple, powerful, reliable, and effective data layer toolkit for Visual Studio.
      Alpha release: Entanglar: Transparant multiplayer framework for .Net games.

      S 1 Reply Last reply
      0
      • M Mark Churchill

        You'll pretty much have to read with timeout. The blocking reads will block in unmanaged code... which prevents things like thread.abort. I normally have "break on thrown" on, and then disable that for all the exceptions that I can't work around. Current app I'm working on is a very large SCADA app - and the only "expected" exceptions come from an SVG library that doesn't have a "TryGetElement" :S

        Mark Churchill Director, Dunn & Churchill Pty Ltd Free Download: Diamond Binding: The simple, powerful, reliable, and effective data layer toolkit for Visual Studio.
        Alpha release: Entanglar: Transparant multiplayer framework for .Net games.

        S Offline
        S Offline
        supercat9
        wrote on last edited by
        #3

        You'll pretty much have to read with timeout. What sort of brilliant designer doesn't allow a 'wait and see if any data comes in, but recognize that a lack of data is also a normal condition' operation? Probably the same one who designed .net 1.0 without things like Date.TryParse I guess. I wish there were some sensible way of enabling the diagnostic messages for exceptions in some cases but not all. In some of my applications there are exceptions which will be somewhat expected though they shouldn't be terribly frequent. In such cases, I sometimes just swallow them (assuming they're of the right type) but the "First chance exception" diagnostics can alert me if they're happening much more often than they should. Is it possible to hook in some sort of event handler for a first-chance exception that could log exceptions that seem suitable (using a thread-safe logging system, of course)?

        C 1 Reply Last reply
        0
        • S supercat9

          You'll pretty much have to read with timeout. What sort of brilliant designer doesn't allow a 'wait and see if any data comes in, but recognize that a lack of data is also a normal condition' operation? Probably the same one who designed .net 1.0 without things like Date.TryParse I guess. I wish there were some sensible way of enabling the diagnostic messages for exceptions in some cases but not all. In some of my applications there are exceptions which will be somewhat expected though they shouldn't be terribly frequent. In such cases, I sometimes just swallow them (assuming they're of the right type) but the "First chance exception" diagnostics can alert me if they're happening much more often than they should. Is it possible to hook in some sort of event handler for a first-chance exception that could log exceptions that seem suitable (using a thread-safe logging system, of course)?

          C Offline
          C Offline
          Colin Angus Mackay
          wrote on last edited by
          #4

          supercat9 wrote:

          Probably the same one who designed .net 1.0 without things like Date.TryParse I guess.

          Okay - I feel that is an unfair comment. I attended a talk last year at Microsoft and what was interesting was that they were saying that there were aspects to C# and the .NET framework that have been on the drawing board since before V1 was released that are only just going into V4. Now, think about this from a business perspective. Do you wait until you have an absolutely perfect product before going to market, or do you go to market earlier with a product that will satisfy most people? If you answer the former then you won't last very long in business because you'd burn through your Venture Capital way before you released anything to the market and your competitors would have stollen all your potential customers. Seriously, ignorant comments like that really piss me off. Yes, the .NET Framework may have its faults but are you seriously telling me that you've never had to cut features or use a workaround because of business and time-to-market pressures?

          * Developer Day Scotland 2 - Free community conference * The Blog of Colin Angus Mackay


          Vogon Building and Loan advise that your planet is at risk if you do not keep up repayments on any mortgage secured upon it. Please remember that the force of gravity can go up as well as down.

          S 1 Reply Last reply
          0
          • C Colin Angus Mackay

            supercat9 wrote:

            Probably the same one who designed .net 1.0 without things like Date.TryParse I guess.

            Okay - I feel that is an unfair comment. I attended a talk last year at Microsoft and what was interesting was that they were saying that there were aspects to C# and the .NET framework that have been on the drawing board since before V1 was released that are only just going into V4. Now, think about this from a business perspective. Do you wait until you have an absolutely perfect product before going to market, or do you go to market earlier with a product that will satisfy most people? If you answer the former then you won't last very long in business because you'd burn through your Venture Capital way before you released anything to the market and your competitors would have stollen all your potential customers. Seriously, ignorant comments like that really piss me off. Yes, the .NET Framework may have its faults but are you seriously telling me that you've never had to cut features or use a workaround because of business and time-to-market pressures?

            * Developer Day Scotland 2 - Free community conference * The Blog of Colin Angus Mackay


            Vogon Building and Loan advise that your planet is at risk if you do not keep up repayments on any mortgage secured upon it. Please remember that the force of gravity can go up as well as down.

            S Offline
            S Offline
            supercat9
            wrote on last edited by
            #5

            I did finally figure out a way to make the serial port work reasonably, using a received-data event to hit a ManualResetEvent (if the main communication thread has set it). The code creates a new ManualResetEvent every time the main thread polls and there isn't any data available; a monitor might be better, but using the ManaulResetEvent makes it possible for another thread to set a 'hurry up and abort the current operation' WaitHandle (which could be used, along with the former, in a WaitAny).

            Okay - I feel that is an unfair comment.

            Since there seems to be a good solution using events, I'd agree that my apparent antipathy toward the authors of the SerialPort class was somewhat misplaced. The Windows communications API has somewhat dubious semantics (which probably go back aeons) and the SerialPort class is mostly just exposing them. The decision to have a timeout error always throw an exception is unfortunate, but the availability of the receive data event makes it possible to emulate the two styles of semantics that a good communications library should support: -1- Wait up to a specified time for 'n' bytes; if fewer than 'n' bytes become available in time, do not return a smaller number, but instead flag an error (or throw an exception). -2- If any data is available, return it. Otherwise, wait up to a specified amount of time (possibly zero) to see if any arrives. The Windows API is a mishmosh of these approaches, so I suppose it makes sense that the SerialPort class would be as well.

            Colin Angus Mackay wrote:

            Do you wait until you have an absolutely perfect product before going to market, or do you go to market earlier with a product that will satisfy most people?

            Maybe I was a bit too sarcastic, but to my mind the concept of a 'try' pattern should be a core part of any non-trivial exception-based code, except in circumstances where it's not practical to predict an operation's success without committing to the operation. Whoever made the first-chance exceptions go to the immediate window was clearly trying to encourage programmers to avoid exceptions when practical; a worthy goal, but one which requires giving programmers the tools to do that. I guess what I find most irksome/puzzling about things like Date.Parse is that I can't imagine that people could use such a function very much without its limitations quickly becoming apparent. If Microsoft had to code around the limitations of something like Date.Parse in o

            1 Reply Last reply
            0
            Reply
            • Reply as topic
            Log in to reply
            • Oldest to Newest
            • Newest to Oldest
            • Most Votes


            • Login

            • Don't have an account? Register

            • Login or register to search.
            • First post
              Last post
            0
            • Categories
            • Recent
            • Tags
            • Popular
            • World
            • Users
            • Groups