I am trying to do some networking in Unity, but I am catching a SendDataSystem.ObjectDisposedException: Cannot access a disposed object. Exception while executing code inside of my using statement.
Images of Code:
- https://i.imgur.com/cBr2ruV.png
- https://i.imgur.com/PTtpml5.png
- https://i.imgur.com/JRYHrC5.png
- https://i.imgur.com/88YsmVn.png
-ClientSend 1
public static void SendItem(int itemLVL, int toStationID)
{
Debug.Log("Sending Item on channel : " + (int)ClientPackets.item);
using (sPacket packet = new sPacket((int)ClientPackets.item))
{
packet.Write(itemLVL);
packet.Write(toStationID);
SendTCPData(packet);
}
}
-ClientSend 2
private static void SendTCPData(sPacket packet)
{
packet.WriteLength();
Client.instance._tcp.SendData(packet);
}
-Client.tcp
public void SendData(sPacket packet)
{
try
{
if (_socket != null)
{
_stream.BeginWrite(packet.ToArray(), 0, packet.Length(), null, null);
}
}
catch (Exception e)
{
Debug.LogError("Error in SendData" + e);
}
}
what would cause a packet to be “disposed of” by the time SendTCPData(packet)
calls Client.instance._tcp.SendData(packet)
then SendData(packet)
catches the exception ObjectDisposedException: Cannot access a disposed object
? I understand that the using(packet)
syntax will auto call Dispose when it ends the block, however I dont understand why the stack is messing this up somehow on its calls down?
Shouldn’t it go :
ClientSend.SendItem() open the using block → ClientSend.SendTCPData() → Client._tcp.SendData() uses data, then stack goes upward and the using block closes?
Note:
The tcp connection was previously opened when connecting