提供大文件异步,然后删除它

时间:2015-04-23 23:18:51

标签: async-await asp.net-web-api2

使用Web API 2,我有一个生成临时文件的过程,目的是将其写入输出流以供客户端使用。这个过程可能需要很长时间才能完成。

我想要做的是异步提供文件,然后在完成或取消(连接超时)后删除它。

这样的事情会接近吗?我还没有测试过,但我想知道继续将文件删除之前完全服务。

public class FileCreationResult
{
    public String FilePathOut { get; set; }
}

public class MyFileCreationProcess{
    const string NaiveDefaultTempFilePath = @"c:\temp\mytempfile.bin";

    public FileCreationResult Execute(){
        // do stuff that makes a file

        File.WriteAllBytes(NaiveDefaultTempFilePath, NaiveDefaultTempFilePath);
        return new FileCreationResult{
            FilePathOut = NaiveDefaultTempFilePath
        };              
    }   
}

public class Controller : ApiController
{
    private readonly MyFileCreationProcess process;

    public Controller(MyFileCreationProcess process)
    {
        this.process = process;
    }

    public async Task<HttpResponse> GetFile(CancellationToken cancellationToken){
        return await Task.Run(()=>{
            var fileCreationResult = process.Execute();         
            using( var stream = File.OpenRead(fileCreationResult.FilePathOut)){
                var response = Request.CreateResponse();                
                response.Content = new StreamContent( stream);
                return response;
                //
                // I would like to delete the file at path fileCreationResult.FilePathOut
                // after it has been written to the output stream..
                // how would I do this ?
            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

你可能只是试一试最终阻止

public async Task<HttpResponse> GetFile(CancellationToken cancellationToken){
    return await Task.Run(()=>{
        var fileCreationResult = process.Execute();
        try{
        using( var stream = File.OpenRead(fileCreationResult.FilePathOut)){
            var response = Request.CreateResponse();                
            response.Content = new StreamContent( stream);
            return response;
        }
        }finally{
           if(File.Exists(fileCreationResult.FilePathOut))
           {
              File.Delete(fileCreationResult.FilePathOut);
           }
        }
    });
}

或者如果您想使用continueWith

public Task<HttpResponse> GetFile(CancellationToken cancellationToken){
    string path;
    return  Task.Run(()=>{
        var fileCreationResult = process.Execute();
        path = fileCreationResult.FilePathOut;

        using( var stream = File.OpenRead(path)){
            var response = Request.CreateResponse();                
            response.Content = new StreamContent( stream);
            return response;
        }
        }).ContinueWith(x=>{
            if(File.Exists(fileCreationResult.FilePathOut))
           {
              File.Delete(fileCreationResult.FilePathOut);
           }
        });
}

我应该注意我没有方便的C#编译器,所以它可能无法编译,但我认为你明白了。