Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 89753
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T22:45:57+00:00 2026-05-10T22:45:57+00:00

If you have a pending operation, eg stream.BeginRead(_buffer, 0, _buffer.Length, _asyncCallbackRead, this); and you

  • 0

If you have a pending operation, eg

stream.BeginRead(_buffer, 0, _buffer.Length, _asyncCallbackRead, this); 

and you close the stream provider, eg

serialPort.Close(); 

you unsurprisingly cause an exception.

Is there an preferred method by which one might cancel a pending APM operation, prior to closing the port?


The world has changed

Use IStream.ReadAsync(Memory<Byte>, CancellationToken)


Colby’s reply is not the answer I hoped for, but he does at least close off a fruitless avenue in inquiry.

Happily I have found a solution.

As noted by a commenter, this will probably leak but as I do this because the app is trying to exit, it hardly matters. You should use a cancellation token anyway.

For each stream I maintain various state information in a class DeviceSession. This class has a method ReadStream providing the implementation for the AsyncCallback that handles incoming data.

Note that _asyncCallbackRead and every other variable beginning with an underscore is a class private member assigned in the constructor of DeviceSession.

The constructor also provides the initial call to _stream.BeginRead.

void ReadStream(IAsyncResult ar) {   if (IsOpen)      try     {       DevicePacket packet;       int cbRead = _stream.EndRead(ar);       _endOfValidData += cbRead;       while ((packet = GetPacket()) != null)         CommandStrategy.Process(this, packet);       _stream.BeginRead(_buffer, _endOfValidData,          _buffer.Length - _endOfValidData,          _asyncCallbackRead, null);     }     catch (Exception ex)     {       Trace.TraceError("{0}\r\n{1}", ex.Message, ex.StackTrace);       _restart(_streamProvider, _deviceId);     } } 

Notice that I haven’t bothered to set ar.AsyncState. Because the callback delegate refers to the method of a specific instance of DeviceSession, detailed and strongly typed context information (contained in the members of this instance of DeviceSession) is automatically in scope. This is the point of having a session object.

Back on the subject of aborting a listener, closing the stream provider triggers the callback but attempting to invoke EndRead results in an IOException.

Generally such an exception indicates a fault requiring a listener restart and one will want to respond by restarting the stream provider and recreating the session. This is complicated by the absence of a reliable stream-provider-independent way to determine whether the provider has faulted or the user is trying to restart the connection (eg plugged a new device into the port).

The trick is to add more context (IsOpen) to the DeviceSession to indicate whether the session is open or has been closed, and use it to smoothly complete the final abortive execution of ReadStream.

If IsOpen is true then an IOException represents a failure in need of recovery. If IsOpen is false the failure was deliberately induced and no action is required.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-10T22:45:58+00:00Added an answer on May 10, 2026 at 10:45 pm

    This is not directly supported in the framework. Your best bet is to write a wrapper that spawns a thread and use synchronization primitives like events to signal a cancel request.

    HTH

    Colby Africa

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 75k
  • Answers 75k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • added an answer You're probably viewing whitespace, duplicate topic here: How do I… May 11, 2026 at 2:38 pm
  • added an answer Check out .NET RIA Services: Build a Simple Application with… May 11, 2026 at 2:38 pm
  • added an answer Javascript can help you with browser detection and figuring out… May 11, 2026 at 2:38 pm

Related Questions

I am implementing an asynchronous command pattern for the client class in a client/server
My C# class must be able to process a high volume of events received
I have an ASP.NET application that renders a 3rd party (Telerik's) menu control under
I have a question regarding the two additional columns (timeCreated, timeLastUpdated) for each record

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.