How to utilize the memory stream that is in the task?

I have the following method

public void Write() { var tasks = new List<Task>(); while(...) { var memoryStream = new MemoryStream(...); var task = _pageBlob.WritePagesAsync(memoryStream, ... ); tasks.Add(task); } Task.WaitAll(tasks.ToArray()); } 

How to properly manage a memoryStream in Task ? I need to delete the memoryStream object when the task is complete.

+5
source share
3 answers

Divide the body of the while into a separate async method:

 private async Task WriteAsync(...) { using (var memoryStream = new MemoryStream(...)) { await _pageBlob.WritePagesAsync(memoryStream, ...); } } 

Then use the new method:

 public void Write() { var tasks = new List<Task>(); while(...) { tasks.Add(WriteAsync(...)); } Task.WaitAll(tasks.ToArray()); } 

On the one hand, blocking asynchronous code ( Task.WaitAll ) is usually not a good idea. A more natural approach is to maintain asynchrony:

 public async Task WriteAsync() { var tasks = new List<Task>(); while(...) { tasks.Add(WriteAsync(...)); } await Task.WhenAll(tasks); } 
+2
source

You have two options:

1-Encapsulate the entire process inside the task:

 while(...) { var task = Task.Run(async () => { var memoryStream = new MemoryStream(...); var res = await _pageBlob.WritePagesAsync(memoryStream, ... ); memoryStream.Dispose(); }); tasks.Add(task); } 

2-Use continuation:

  while(...) { var memoryStream = new MemoryStream(...); var task = _pageBlob.WritePagesAsync(memoryStream, ... ) .ContinueWith((PrevTask) => memoryStream.Dispose()); tasks.Add(task); } 
+3
source

I would do something like this:

 public void Write() { var tasks = new List<Task>(); while (...) { var memoryStream = new MemoryStream(...); var task = WritePagesAsync(memoryStream, ...); tasks.Add(task); } Task.WaitAll(tasks.ToArray()); } private async Task WritePagesAsync(MemoryStream memoryStrem, ...) { await _pageBlob.WritePagesAsync(memoryStrem); memoryStrem.Dispose(); } 
0
source

All Articles