我有以下方法:
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()); }
如何在Task中正确处理memoryStream?我需要在任务完成时处理memoryStream对象.
解决方法
将while循环体拆分为单独的异步方法:
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); }