WebClient不支持并发I / O操作

时间:2012-12-02 07:19:15

标签: c# .net io

我做了@Enigmativity写的 这是:

        Action<int, ProgressBar, Label, Label, int, Button> downloadFileAsync = (i, pb, label2, label1, ServID, button1) =>
    {
        var bd = AppDomain.CurrentDomain.BaseDirectory;
        var fn = bd + "/" + i + ".7z";
        var down = new WebClient();
        DownloadProgressChangedEventHandler dpc = (s, e) =>
        {
            label1.Text = "Download Update: " + i + " From: " + ServID;
            int rec =Convert.ToInt16(e.BytesReceived / 1024);
            int total =Convert.ToInt16(e.TotalBytesToReceive / 1024)  ;
            label2.Text = "Downloaded: " + rec.ToString() + " / " + total.ToString() + " KB";
            pb.Value = e.ProgressPercentage;
        };
        AsyncCompletedEventHandler dfc = null;  dfc = (s, e) =>
        {
            down.DownloadProgressChanged -= dpc;
            down.DownloadFileCompleted -= dfc;
            CompressionEngine.Current.Decoder.DecodeIntoDirectory(AppDomain.CurrentDomain.BaseDirectory + "/" + i + ".7z", AppDomain.CurrentDomain.BaseDirectory);
            File.Delete(fn);
               if (i == ServID)
                {

                   button1.Enabled = true;
                   label1.Text = "Game Is Up-To-Date.Have Fun!!";
                  label2.Text = "Done..";
               }
         down.Dispose();
        };

我现在唯一的问题是当程序提取下载的文件时

CompressionEngine.Current.Decoder.DecodeIntoDirectory(AppDomain.CurrentDomain.BaseDirectory + "/" + i + ".7z", AppDomain.CurrentDomain.BaseDirectory);

在某些文件中,需要时间来取消下载的文件 那么我怎么能告诉程序要等到解压缩完成呢?

1 个答案:

答案 0 :(得分:2)

尝试定义一个将封装单个异步下载的lambda,然后在循环中调用它。

这是lambda:

Action<int> downloadFileAsync = i =>
{
    var bd = AppDomain.CurrentDomain.BaseDirectory;
    var fn = bd + "/" + i + ".7z";
    var wc = new WebClient();
    DownloadProgressChangedEventHandler dpc = (s, e) =>
    {
        progressBar1.Value = e.ProgressPercentage;
    };
    AsyncCompletedEventHandler dfc = null;
    dfc = (s, e) =>
    {
        wc.DownloadProgressChanged -= dpc;
        wc.DownloadFileCompleted -= dfc;
        CompressionEngine.Current.Decoder.DecodeIntoDirectory(fn, bd);
        File.Delete(fn);
        wc.Dispose();
    };
    wc.DownloadProgressChanged += dpc;
    wc.DownloadFileCompleted += dfc;
    wc.DownloadFileAsync(new Uri(Dlpath + i + "/" + i + ".7z"), fn);
};

您会注意到它很好地分离了所有事件并正确处理了WebClient实例。

现在这样称呼:

while (i <= ServID)
{
    downloadFileAsync(i);
    i++;
}

您必须调整进度条更新以正确显示所有文件下载的进度,但原则上这应该适合您。