Skip to content

fix(stdio): handle ObjectDisposedException from disposed NetworkStream during domain reload#1251

Open
beast-ofcourse wants to merge 1 commit into
CoplayDev:betafrom
beast-ofcourse:fix/stdio-disposed-networkstream-reload
Open

fix(stdio): handle ObjectDisposedException from disposed NetworkStream during domain reload#1251
beast-ofcourse wants to merge 1 commit into
CoplayDev:betafrom
beast-ofcourse:fix/stdio-disposed-networkstream-reload

Conversation

@beast-ofcourse

@beast-ofcourse beast-ofcourse commented Jul 7, 2026

Copy link
Copy Markdown

Problem

After domain reload or compilation, StdioBridgeHost logs an error: Cannot access a disposed object. Object name: 'System.Net.Sockets.NetworkStream'. While the HandleClientAsync outer catch already treats ObjectDisposedException as benign, the I/O methods (ReadExactAsync, WriteFrameAsync) throw it raw, making the code depend on a single catch block for correctness.

Fixes #1232

Root Cause

During domain reload, Stop() closes all active TcpClient connections via c.Close(). Any pending async read/write on the underlying NetworkStream throws ObjectDisposedException. While this is caught and treated as benign at the HandleClientAsync outer catch, the exception type is inconsistent — ReadExactAsync and WriteFrameAsync throw ObjectDisposedException while every other connection-closed scenario throws IOException.

Solution

Two defensive changes at the I/O boundary:

  1. ReadExactAsync: Added catch (ObjectDisposedException) that throws IOException("Connection closed before reading expected bytes") — matching the existing pattern when stream.ReadAsync returns 0 bytes.

  2. WriteFrameAsync: Wrapped the WriteAsync calls in a try/catch that converts ObjectDisposedException to IOException("Connection closed before writing frame").

This follows the standard .NET pattern where disposed network resources throw IOException rather than ObjectDisposedException, and ensures consistent handling at every level of the stack.

Verification

  • The existing top-level benign check (|| ex is IOException) now catches disposed-stream scenarios uniformly — previously it only caught ObjectDisposedException which was fragile.
  • Read and write paths are both covered.
  • No behavioral change during normal operation — only the exception type changes during shutdown races.

Notes

  • The WriteFrameAsync try/catch adds a small indentation change for the preprocessor conditional body, but no logic changes beyond the new catch block.

Summary by CodeRabbit

  • Bug Fixes
    • Improved error handling when a connection closes unexpectedly during read or write operations.
    • Read failures now report a clearer I/O error if the expected data cannot be received.
    • Write failures now report a clearer I/O error if a frame cannot be fully sent before the connection closes.

…m during domain reload

During domain reload, Stop() closes all active TcpClient connections. Any
pending ReadAsync/WriteAsync on the disposed NetworkStream throws
ObjectDisposedException. The existing top-level catch in HandleClientAsync
already treats this as benign (ex is ObjectDisposedException), but the I/O
methods should also handle it defensively so the exception type is consistent
throughout the stack.

Fix:
- In ReadExactAsync: catch ObjectDisposedException and throw IOException
  with a clear 'Connection closed' message — the standard .NET pattern.
- In WriteFrameAsync: wrap the WriteAsync calls in try/catch for
  ObjectDisposedException, same treatment.

This ensures the disposed-stream scenario is handled uniformly as an
IOException at every level, not just one catch block.

Fixes CoplayDev#1232
@coderabbitai

coderabbitai Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7d9861eb-f44e-4305-8d73-fe93995609f2

📥 Commits

Reviewing files that changed from the base of the PR and between 484937c and 7d25ce1.

📒 Files selected for processing (1)
  • MCPForUnity/Editor/Services/Transport/Transports/StdioBridgeHost.cs

📝 Walkthrough

Walkthrough

ReadExactAsync and WriteFrameAsync in StdioBridgeHost.cs now catch ObjectDisposedException and rethrow it as an IOException with a descriptive message, rather than letting the disposal exception propagate directly.

Changes

Disposed Connection Error Handling

Layer / File(s) Summary
Convert disposed-stream exceptions to IOException
MCPForUnity/Editor/Services/Transport/Transports/StdioBridgeHost.cs
ReadExactAsync and WriteFrameAsync now catch ObjectDisposedException and rethrow it as an IOException describing that the connection closed before the read/write completed.

Estimated code review effort: 1 (Trivial) | ~5 minutes

Possibly related PRs

  • CoplayDev/unity-mcp#1198: Also modifies StdioBridgeHost.cs to treat ObjectDisposedException as a benign/IO condition during connection teardown.

Suggested labels: bug, transport

Suggested reviewers: none

🐰 A stream once closed, an object gone,
Now wrapped in IOException, calmly drawn,
No more disposed errors loudly cried,
Just a tidy message when connections have died.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the disposed-NetworkStream fix during domain reload.
Description check ✅ Passed The description explains the bug, root cause, fix, and verification, but omits several template sections like type, compatibility, and testing.
Linked Issues check ✅ Passed The code normalizes disposed NetworkStream failures to IOException in both read and write paths, matching the issue's shutdown-race fix.
Out of Scope Changes check ✅ Passed The changes stay within StdioBridgeHost and only address disposed-stream handling; no unrelated edits are indicated.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Client handler error: Cannot access a disposed object

1 participant