在大约40个图像下载后,.NET Parallel Task.Factory.StartNew不起作用

时间:2014-01-02 22:08:37

标签: .net multithreading winforms parallel-processing imagedownload

我有一个Winform应用程序。单击button2后,应用程序将开始下载大量图像,其中url存储在ThousandsOfImageURL列表中。该应用程序适用于前40个图像下载。但在此之后,函数ParallelRunBrowser中的Task.Factory.StartNew无法启动RunBrowserThread。我可以看到每10秒就会遇到Task.Factory.StartNew但是在下载了大约40个图像之后,类DownLoadImages的RunBrowserThread内的断点不能再被击中了。我没有看到任何例外情况在几个小时内被抛出。

可能的问题是什么?

谢谢,

    private void button2_Click(object sender, EventArgs e)
    {
        var sta = new StaTaskScheduler(numberOfThreads: 4);
        var doImages = new ThreadLocal<DownLoadImages>(() => new DownLoadImages());

        foreach (string url in ThousandsOfImageURLs)
              ParallelRunBrowser(strSiteRoot + url, sta, doImages);
            }
        }
    }

    private void ParallelRunBrowser(string url, StaTaskScheduler sta, ThreadLocal<DownLoadImages> doImages)
    {
        Thread.Sleep(10000);

            Task.Factory.StartNew(() =>
            {
                doImages.Value.RunBrowserThread(new Uri(url));
            },
            CancellationToken.None,
            TaskCreationOptions.None,
            sta);
    }


class DownLoadImages
{
    public void RunBrowserThread(Uri url)
    {
            var br = new WebBrowser();
            br.DocumentCompleted += Browser_DocumentCompleted;
            br.Navigate(url);
            Application.Run();
    }

    void Browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        var br = sender as WebBrowser;
        if (br.Url == e.Url)
        {
                FinishDownLoadHere(sender, e);
                Application.ExitThread();   
                ((WebBrowser)sender).Dispose();
                GC.Collect();
        }
    } 
}

1 个答案:

答案 0 :(得分:2)

使用webbrowsers,Application.Run和GC.collect似乎有点多了。

为什么不使用WebClient来获取图像?

来自:Download image from the site in .NET/C#

string localFilename = @"c:\localpath\tofile.jpg";
using(WebClient client = new WebClient())
{
    client.DownloadFile("http://www.example.com/image.jpg", localFilename);
}