如何处置Task中使用的MemoryStream?

时间:2016-04-28 14:18:03

标签: c# multithreading

我有以下方法:

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

如何正确处理memoryStream中的Task?我需要在任务完成时处理memoryStream对象。

3 个答案:

答案 0 :(得分:4)

您有两种选择:

1 - 封装任务中的所有进程:

while(...) {

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

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

     });

     tasks.Add(task);
 }    

2 - 使用延续:

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

     tasks.Add(task);
 }    

答案 1 :(得分:3)

while循环体拆分为单独的async方法:

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

然后使用您的新方法:

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

另一方面,阻止异步代码(Task.WaitAll)通常不是一个好主意。更自然的方法是保持异步:

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

答案 2 :(得分:0)

我会做这样的事情:

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