The thread is likely to be closed and deleted before the task completes. This throws an ObjectDisposedException:
using(MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes("abc"),0,3)) { Task.Run(() => { Thread.Sleep(100); ms.Read(new byte[3], 0, 3); }); }
you can transfer the using statement to close the task, or you can wait for the task to complete, for example:
using(MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes("abc"),0,3)) { await Task.Run(() => { Thread.Sleep(100); var bytes = new byte[3]; ms.Read(bytes, 0, 3); Console.WriteLine(Encoding.ASCII.GetString(bytes)); }); }
source share