我有一个异步读取的 NetworkStream(使用 async/await)
await Task<int>.Factory.FromAsync((cb, state) => stream.BeginRead(buffer, offset, readLen - offset), stream.EndRead, null);
不幸的是,有时会发生 io 异常:“由于线程退出或应用程序请求,I/O 操作已中止。”
我相信我达到了 Socke.EndReceive 中记录的要求:http://msdn.microsoft.com/en-us/library/w7wtt64b.aspx .其中指出:
All I/O initiated by a given thread is canceled when that thread exits. A pending asynchronous operation can fail if the thread exits before the operation completes.
因为异步方法在默认调度程序上运行,所以无法保证这一要求。
有解决办法吗?我需要启动一个专用线程来启动 I/O 吗?
最好的问候,德克
最佳答案
我在 parallelextensions 论坛上问过同样的问题:
基本上,ThreadPool 不会停止任何具有异步 I/O 挂起的线程。所以只要在ThreadPool上启动socket操作就不会出现这个问题。
关于c# - 异步套接字读取 : the initiating thread must not be exited - what to do?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7242155/