加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用Async / Await时Stream正在关闭

发布时间:2020-12-16 02:01:38 所属栏目:百科 来源:网络整理
导读:我有一点服务将blob上传到Azure存储.我试图从WebApi异步操作中使用它,但我的AzureFileStorageService说流已关闭. 我是async / await的新手,是否有任何好的资源可以帮助我更好地理解它? WebApi控制器 public class ImageController : ApiController{ private
我有一点服务将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();
    }
}

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
    }
}

解决方法

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

相反,您将不得不在调用方法中返回Task和await,或者您将不得不在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();
    }

和Save方法:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读