Reading an asynchronous socket: the initiating stream should not exit - what should I do?

I have a NetworkStream that I read asynchronously (using async / wait)

await Task<int>.Factory.FromAsync((cb, state) => stream.BeginRead(buffer, offset, readLen - offset), stream.EndRead, null); 

Unfortunately, an io exception sometimes occurs: "The I / O operation was interrupted due to a stream or application request."

I believe that I applied the requirement registered in Socke.EndReceive: http://msdn.microsoft.com/en-us/library/w7wtt64b.aspx . What are the conditions:

All I / O initiated by this stream is canceled when this stream exits. The expected asynchronous operation may fail if the thread completes before the operation completes.

Since the async method works in the scheduler by default, this requirement cannot be guaranteed.

Is there any way around this? Do I need to run a dedicated thread to initialize I / O?

Regards, Dirk

+6
source share
3 answers

I asked the same question in the parallelextensions forum:

http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/d116f7b0-c8ee-4ce4-a9b8-4c38120e45a4

Basically, ThreadPool will not stop a single thread on which asynchronous I / O operations are expected. As long as you run the socket operation on ThreadPool, this problem should not occur.

+3
source

I would recommend using dedicated I / O streams that never end. This is what makes a lot of real code.

One of the best ways to do this is to bundle threads around GetQueuedCompletionStatus . If you need to do one of the I / O streams by performing an I / O operation, call PostQueuedCompletionStatus or QueueUserAPC to get the I / O stream to publish the operation.

CAUTION You must handle the case where these operations fail. QueueUserAPC , for example, can fail if too many APCs are already queued.

+1
source

You can use the oldest trick in the book. Make a thread in an infinite loop

 while(true) { Threading.Sleep(TimeSpan.FromSeconds(1); } 

Please note that I wrote the code above from my head. I have not tested it in Visual Studio since I'm working on my Mac right now.

You will also need to write something to exit the stream when you need to, but it will depend on how your application flows.

-1
source

Source: https://habr.com/ru/post/896196/


All Articles