在异步任务中关闭MemoryStream

时间:2014-07-07 17:36:26

标签: c# task async-await

我正在编写代码,一次加载同一任务的多个实例,并等待它们全部完成。每个任务都从一个文件中读取并上传该文件的一部分的字节数组。

var requests = new Task[parts.Count];
foreach (var part in parts)
{
    var partNumber = part.Item1;
    var partSize = part.Item2;
    var ms = new MemoryStream(partSize);
    var bw = new BinaryWriter(ms);

    var offset = (partNumber - 1) * partMaxSize;
    var count = partSize;
    bw.Write(assetContentBytes, offset, count);

    ms.Position = 0;
    Console.WriteLine("beginning upload of part " + partNumber);
    requests[partNumber - 1] = uploadClient.UploadPart(uploadResult.AssetId, partNumber, ms);
}

await Task.WhenAll(requests);

我想在相关任务完成后关闭这些MemoryStream,但是如果我将stream.Close()写入循环,则在任务完成之前关闭流。任务完成后是否可以关闭每个流?感谢。

1 个答案:

答案 0 :(得分:10)

只需将使用该流的部分提取到另一个异步方法:

    var requests = new Task[parts.Count];
    foreach (var part in parts)
    {
        var partNumber = part.Item1;
        var partSize = part.Item2;
        requests[partNumber - 1] = UploadPartAsync(partNumber, partSize);
    }

    await Task.WhenAll(requests);

...

async Task UploadPartAsync(int partNumber, int partSize)
{
    using (var ms = new MemoryStream(partSize))
    using (var bw = new BinaryWriter(ms))
    {
        var offset = (partNumber - 1) * partMaxSize;
        var count = partSize;
        bw.Write(assetContentBytes, offset, count);

        ms.Position = 0;
        Console.WriteLine("beginning upload of part " + partNumber);
        await uploadClient.UploadPart(uploadResult.AssetId, partNumber, ms);
    }
}