c# - 异步套接字读取 : the initiating thread must not be exited - what to do?

标签 c# multithreading asynchronous threadpool task-parallel-library

我有一个异步读取的 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 论坛上问过同样的问题:

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

基本上,ThreadPool 不会停止任何具有异步 I/O 挂起的线程。所以只要在ThreadPool上启动socket操作就不会出现这个问题。

关于c# - 异步套接字读取 : the initiating thread must not be exited - what to do?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7242155/

相关文章:

javascript - 无法使用 PUT 方法更新行 - MVC 4?

c# - 如何获取两个 Point 对象之间的所有点?

python - python同时等待并通知多个线程

multithreading - 如何检查事件循环是否有线程外的挂起事件?

javascript - 返回 promise 的函数必须是异步的

javascript - 如何使用一系列异步请求的结果填充数组

c# - 似乎没有为 __doPostBack 发出正确的 GridView 标记

c# - 如何使用多个嵌套的三元运算符返回一个值

multithreading - perl 系统调用在使用线程时导致挂起

swift - 如何使用转义闭包和异步调用加载 UI?