低优先级http文件传输?

时间:2010-02-10 03:58:26

标签: .net http

是否有一种简单的方法来创建文件的低优先级传输?我的服务器上有很多文件,有时我也会传输其他东西。有一种简单的方法可以让我的网络繁忙时我的应用程序传输缓慢吗?

2 个答案:

答案 0 :(得分:3)

结帐BITS。以下是转移为低优先级的快速示例:

    using (var done = new EventWaitHandle(false, EventResetMode.ManualReset))
    {
        var manager = new Manager();
        var job = manager.CreateJob("Test Job Name");
        var jobevents = new JobEvents();

        job.AddFile(
            @"F:\DEV\TestBITS\TestBITS\dotnetfx35.exe",
            "http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe");
        job.Priority = JobPriority.Low;
        jobevents.JobTransferred += (sender, e) => { e.Job.Complete(); done.Set(); };
        jobevents.JobError += (sender, e) => { e.Job.Cancel(); done.Set(); };
        jobevents.AddJob(job);
        job.ResumeJob();
        done.WaitOne();
    }

答案 1 :(得分:1)

使用WebClient.OpenRead并在阅读回复的过程中添加一些睡眠。这些方面的东西:

using(var client = new WebClient())
using(var input = client.OpenRead("http://whatever.com/myfile.txt"))
using(var output = File.OpenWrite("c:/temp/myfile.txt"))
{
    var length = long.Parse(client.ResponseHeaders["content-length"]);
    var buffer = new byte[32768];
    long totalRead = 0;
    while(totalRead < length)
    {
        int read = input.Read(buffer, 0, buffer.Length);
        if (read != 0)
        {
            output.Write(buffer, 0, read);
            totalRead += read;
        }
        Thread.Sleep(100); // This is what slows down the download, make number bigger to download slower
    }
}