简体   繁体   中英

How to dispose a MemoryStream that is used in a 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 correctly dispose memoryStream that in Task ? I need to dispose the memoryStream object when the task is finished.

You have two options:

1-Encapsulate all the process inside a task:

while(...) {

     var task = Task.Run(async () => {

         var memoryStream = new MemoryStream(...);
         var res = await _pageBlob.WritePagesAsync(memoryStream, ... );
         memoryStream.Dispose();

     });

     tasks.Add(task);
 }    

2-Use a Continuation:

 while(...) {
     var memoryStream = new MemoryStream(...);
     var task = _pageBlob.WritePagesAsync(memoryStream, ... )
                .ContinueWith((PrevTask) => memoryStream.Dispose());

     tasks.Add(task);
 }    

Split out your while loop body into a separate async method:

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

Then use your new method:

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

On a side note, blocking on asynchronous code ( Task.WaitAll ) is not generally a good idea. A more natural approach is to keep it asynchronous:

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

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM