I'm attempting to dispose of a NetworkStream
after it's finished writing. I've tried wrapping the stream in a using()
like so:
using (NetworkStream stream = client.GetStream())
{
foreach (byte[] command in fadeSceneOut)
{
if (stream.CanWrite)
{
stream.BeginWrite(command, 0, command.Length, new AsyncCallback(SendCallback), stream);
}
}
}
But I receive a System.ObjectDisposedException
stating that the object has already been disposed and cannot be accessed in my callback where I send an EndWrite()
:
private static void SendCallback(IAsyncResult ar)
{
try
{
NetworkStream stream = (NetworkStream)ar.AsyncState;
stream.EndWrite(ar);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
My understanding was that the stream would not be disposed until execution leaves the using
block after all commands have been written to the stream. Obviously I've gotten something wrong here, can someone advise on the correct approach?
Edit: included an await
approach:
static void Main(string[] args)
{
Task.WaitAll(Run());
}
public static async Task Run()
{
// Get a scene
var scene = GrabSceneFromUser();
// Get scene commands
var fadeSceneIn = LightSwarmHelper.BuildSceneCommands(scene);
var fadeSceneOut = LightSwarmHelper.BuildSceneCommands(scene, false);
// Send commands to device
using (TcpClient client = new TcpClient(ConfigurationManager.AppSettings["Host"], Convert.ToInt32(ConfigurationManager.AppSettings["Port"])))
{
using (NetworkStream stream = client.GetStream())
{
foreach (byte[] command in fadeSceneOut)
{
if (stream.CanWrite)
{
await stream.WriteAsync(command, 0, command.Length); //stream.BeginWrite(command, 0, command.Length, new AsyncCallback(SendCallback), stream);
}
}
}
}
}