Is it possible to call Task.Run inside a using statement?

Code like this, I want to put most of the work into Task.Run, but I'm not sure if the using statement will work as expected.

using(MemoryStream ms = new MemoryStream()) { Task.Run(() => { /* capture ms and process the stream */ } } // Will ms will be disposed here automatically? 

Thanks.

+5
source share
2 answers

No. Deleting a thread can be done before your task completes. You would be better off putting usage inside the task if possible, or manually handle the deletion at the end of the task.

 var ms = new MemoryStream(); Task.Run(() => { /* capture ms and process the stream */ // Dispose of the stream manually when you are done ms.Dispose(); } 

Note that if you use a memory stream outside the task, then you run the risk of using it after deleting it. If you can, use only the thread inside the task and save the results in another place.

 Task.Run(() => { using(var ms = new MemoryStream()) { /* capture ms and process the stream */ } } 
+5
source

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)); }); } 
+3
source

Source: https://habr.com/ru/post/1259790/


All Articles