使用Async/Await时Stream正在关闭

Sam*_*Sam 3 c# asynchronous azure asp.net-web-api

我有一点服务将blob上传到Azure存储.我试图从WebApi异步操作中使用它,但我AzureFileStorageService说流已关闭.

我是async/await的新手,是否有任何好的资源可以帮助我更好地理解它?

WebApi控制器

public class ImageController : ApiController
{
    private IFileStorageService fileStorageService;

    public ImageController(IFileStorageService fileStorageService)
    {
        this.fileStorageService = fileStorageService;
    }

    public async Task<IHttpActionResult> Post()
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
        }

        await Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider()).ContinueWith((task) =>
        {

            foreach (var item in task.Result.Contents)
            {
                using (var fileStream = item.ReadAsStreamAsync().Result)
                {
                    fileStorageService.Save(@"large/Sam.jpg", fileStream);
                }

                item.Dispose();
            }

        });

        return Ok();
    }
}
Run Code Online (Sandbox Code Playgroud)

AzureFileStorageService

public class AzureFileStorageService : IFileStorageService
{
    public async void Save(string path, Stream source)
    {
        await CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"])
            .CreateCloudBlobClient()
            .GetContainerReference("images")
            .GetBlockBlobReference(path)
            .UploadFromStreamAsync(source); // source throws a stream is disposed exception
    }
}
Run Code Online (Sandbox Code Playgroud)

dle*_*lev 7

您的Save()方法有问题:您没有返回任务,因此调用方法无法等待它完成.如果你只是想解雇并忘记它,那就没问题了,但是你不能这样做,因为你传入的流将在Save()方法返回后立即处理(感谢using语句).

相反,你将不得不返回一个Taskawait在调用方法中,或者你将不得不在using块中有文件流,而是让Save()方法在完成时处理它.

您可以重写代码的一种方法如下:

(调用方法片段):

    var result = await Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider());
    foreach (var item in result.Contents)
    {
        using (var fileStream = await item.ReadAsStreamAsync())
        {
            await fileStorageService.Save(@"large/Sam.jpg", fileStream);
        }

        item.Dispose();
    }
Run Code Online (Sandbox Code Playgroud)

和Save方法:

public async Task Save(string path, Stream source)
{
    await CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"])
        .CreateCloudBlobClient()
        .GetContainerReference("images")
        .GetBlockBlobReference(path)
        .UploadFromStreamAsync(source);
}
Run Code Online (Sandbox Code Playgroud)