我有一个小型的服务来上传blob到Azure Storage。我试图从WebApi的异步操作中使用它,但我的说流已关闭。
我对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();
}
}
AzureFileStorageService(Azure文件存储服务)
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
}
}
async
和await
进行设置;using
块可能会在你获取结果之前过早地关闭流。 - Robert Harveyitem.Dispose()
和Result
上的Dispose()
都会被调用,而Result
是一个Stream
? - SamSave()
方法存在问题:你没有返回一个Task
,因此调用该方法的方法无法等待它完成。因此,在你调用它之后,你离开了using
块并且流被释放,很可能在保存完成之前就已经被释放了。 - dlevitem.Dispose()
是可以的:using
语句正在处理流,而不是项目。 - dlev