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

Related Questions

Background This question is in two parts. I have a one-way WCF operation hosted
I have to choose an online WYSIWYG editor. I'm pending between TinyMCE and Xinha
I have to queries: select id, name, num from pending id, name, num 1,
TFS shows some pending changes under my name, but I have not changed anything.
Is there a way to cancel a pending operation (without disconnect) or set a
Have just started using Google Chrome , and noticed in parts of our site,
Have you ever seen any of there error messages? -- SQL Server 2000 Could
Have you guys had any experiences (positive or negative) by placing your source code/solution
Have just started using Visual Studio Professional's built-in unit testing features, which as I
Have you used VS.NET Architect Edition's Application and System diagrams to start designing a

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.