在循环c#.net中不会触发DownloadFileCompleted事件

时间:2010-02-15 20:58:54

标签: c# .net webclient

我有点困惑,为什么文件下载后事件不会触发。

它自己下载的文件非常好。

我假设我使用它的方式有一些错误,因为事件不会在循环中触发。

感谢任何人都可以给我的帮助

class DownloadQueue
{
    public List<string[]> DownloadItems { get; set; }
    public int CurrentDownloads;
    public int DownloadInProgress;
    string url = @"http://www.google.co.uk/intl/en_uk/images/logo.gif";
    bool downloadComplete;

    public DownloadQueue()
    {
        CurrentDownloads = 0;
        DownloadItems = new List<string[]>();
        Console.Write("new download queue made");
    }

    public void startDownloading(int maxSimulatiousDownloads)
    {
        downloadComplete = true;
        DownloadInProgress = 0;
        WebClient client = new WebClient();
        client.DownloadFileCompleted +=
                    new AsyncCompletedEventHandler(this.downloadCompleteMethod);


            while(DownloadInProgress != DownloadItems.Count )
            {
                if (downloadComplete == true)
                {
                    downloadComplete = false;          

                    client.DownloadFileAsync(new Uri(DownloadItems.ElementAt(DownloadInProgress).ElementAt(0).ToString()), DownloadItems.ElementAt(DownloadInProgress).ElementAt(1).ToString());                        
                }
            }
        Console.Write("all downloads completed");
    }

    private void downloadCompleteMethod(object sender, AsyncCompletedEventArgs e)
    {            
        downloadComplete = true;
        DownloadInProgress++;
        Console.Write("file Downloaded");
    }

    }

2 个答案:

答案 0 :(得分:-1)

您还在等待DownloadFileAsync()调用完成?怎么样的

manualResetEvent AllDone = new mre(false)

在console.WriteLine之前

AllDone.WaitOne()

并在下载完成

if (interlocked.decrement(ref downloadComplete) == 0) { AllDone.Set(); }

答案 1 :(得分:-1)

很可能没有时间传递消息。我怀疑如果你在循环结束时放置一个Application.DoEvents,它会开始触发事件。使用它并不理想,但是根据你的设计,我想不出更好的方法。