简体   繁体   English

为什么在使用PushStreamContent时需要此Sleep?

[英]Why is this Sleep needed when using PushStreamContent?

Referring to this sample code on GitHub: https://github.com/DblV/StreamingWebApi/blob/master/StreamingService/StreamingService/Controllers/StreamingController.cs 在GitHub上参考以下示例代码: https : //github.com/DblV/StreamingWebApi/blob/master/StreamingService/StreamingService/Controllers/StreamingController.cs

I want to stream content stored in a database, which my query returns as a sequence of blobs (essentially one file split into "blocks"). 我想流式传输存储在数据库中的内容,我的查询以一系列Blob(实际上是一个文件分成“块”)的形式返回。 Due to the potential size of the complete response, I want to stream it, and I am following the above example as follows: 由于完整响应的潜在大小,因此我想对其进行流式处理,并按照以下示例进行操作:

public class FileController : ApiController
{
    [HttpGet]
    public HttpResponseMessage Get(string id, [FromUri] string contentType)
    {
        var message = new HttpResponseMessage(HttpStatusCode.OK);
        message.Content = new PushStreamContent((stream, content, context) =>
        {
            GetFileContent(stream, int.Parse(id));
            Thread.Sleep(1000);
            stream.Close();
        });
        message.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);

        return message;
    }

    private void GetFileContent(Stream stream, int id)
    {
        var result = Query(reader => reader.GetStream(0), id);

        foreach (var b in result)
        {
            b.CopyToAsync(stream);
            stream.Flush();
        }
    }

    private IEnumerable<Stream> Query(Func<DbDataReader,Stream> func, int id)
    {
        var command = // Not shown - SELECT command creating the result set

        var reader = command.ExecuteReader();
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                yield return func(reader);
            }
        }

        reader.Close();
    }

Note the use and placement of Thread.Sleep . 注意Thread.Sleep的使用和放置。 When I test this in the browser, the content downloads to a file, but without the Sleep , it hangs at the point of completion; 当我在浏览器中对此进行测试时,内容将下载到文件中,但没有Sleep ,它会在完成时挂起; with the Sleep , it completes properly, and the resulting download is perfect. 使用Sleep ,它可以正常完成,并且最终的下载是完美的。

My question: what is the Sleep doing that averts the hang condition? 我的问题是: Sleep在做什么可以避免挂起状况? My suspicion is that this is more of a work-around than a proper solution; 我怀疑这更多是一种变通办法,而不是适当的解决方案。 if so, what should I be doing instead? 如果是这样,我应该怎么做?

Found that it is a mistake on my part. 发现这是我的错误。 I was incorrectly using CopyToAsync where I should be using CopyTo . 我错误地使用了CopyToAsync ,而应该使用CopyTo Correcting this mistake, it works just fine. 更正此错误,效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM