【问题标题】:Unable to create multiple connections to download file in c#无法创建多个连接以在 C# 中下载文件
【发布时间】:2013-11-02 07:15:07
【问题描述】:

这是我的代码:

 public static Stream CreateLink(Uri path, int start, int end)
        {
            HttpWebResponse response;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(path);
            request.Timeout = 30000;
            request.AddRange(start, end);
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch
            {
                response = null;
            }
            if (response != null)
            {
                var stream = response.GetResponseStream();
                return stream;
            }
            return null;
        }

我正在创建多个连接以从同一流中并行下载数据。但是,它只返回一次流并在所有后续尝试中返回 null,直到第一个返回的流关闭。
此外,Stream 支持 Accept-Rangesbytes
所以,我的问题是如何建立多个连接或者我上面的代码有问题吗?


更新:
response 设置为 null 由于超时异常,或者在关闭之前的连接(响应流)之前没有响应。

【问题讨论】:

  • I am creating multiple connections to download data in parallel 到底在哪里?我在您的代码中没有看到它。
  • 我在多个线程上调用CreateLink() 并从返回的流中并行下载

标签: c# .net stream download


【解决方案1】:

.NET Framework 4/4.5 具有内置优化的异步 HttpClient 类。您可以使用它们从 HTTP 实现几乎所有您想要的。这就是您所需要的一切:

var responseMessage = await (new HttpClient().GetAsync("http://download.linnrecords.com/test/flac/recit24bit.aspx", HttpCompletionOption.ResponseHeadersRead));
if (responseMessage.StatusCode == System.Net.HttpStatusCode.OK)
{
    var filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test_http_download.flac");
    using (var fileStream = File.Create(filePath))
    using (var httpStream = await responseMessage.Content.ReadAsStreamAsync())
    {
        httpStream.CopyTo(fileStream);
        fileStream.Flush();
    }
    Process.Start(filePath);
}

【讨论】:

    【解决方案2】:

    似乎大多数时候您不会在 HttpWebRequest 中获得长度,这就是为什么在尝试运行代码时会出现以下异常:

    This stream does not support seek operations.

    和:

    'debug.Position' threw an exception of type 'System.NotSupportedException'

    查看this 答案了解更多详情:)

    编辑: 我不确定你是如何调用你的代码以及从哪里调用的,但如果你以正常的程序(串行)方式进行调用,例如:

    for (int i =0; i<10; i++) {
      var some_var = CreateLink(path, i*100,(i+1)*100)
    }
    

    然后它显然会调用该方法,等到它获得前 100 个(或任何你设置的)字节,然后再次调用它。

    【讨论】:

    • 我没有得到这样的异常,因为我没有使用 seek 操作。我只是得到超时异常,或者我不能一次创建多个活动连接。
    • 另附注:我有长度,否则我不会有开始和结束
    • 这是我尝试你的代码时遇到的错误,你能给我你正在使用的链接吗?
    猜你喜欢
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 2021-01-22
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    相关资源
    最近更新 更多