使用方法副本启动任务

时间:2017-04-14 08:27:30

标签: c# .net

我正在尝试制作一个可以通过WebRequest和Streams同时下载两个文件的下载程序。

根据我的理解,当我开始新任务时,他们会分享相同的方法吗?

这使得两个文件的下载变得不可能,是否有办法创建新任务或创建方法副本的线程?

我尝试了什么:

for (int i = 0; i < dataGridView.RowCount; i++) // 
{
    for (m_ThreadIndex = 0; m_ThreadIndex < 2; m_ThreadIndex++)
    {
        m_Downloader.DownloadProgressChanged += DownloadProgressChanged;
        m_Downloader.DownloadCompleted += DownloadCompleted;
        var i1 = i;
        Task.Factory.StartNew(() => m_Downloader.Start(i1));
        i++;
    }
    Task.WaitAll();
}

1 个答案:

答案 0 :(得分:1)

正如Jeroen van Lagen所说,不可能制作方法的副本。您可以改为创建一个新类并将该方法放在类中。然后,您可以创建多个类实例。

Class MyMainClass
{
    private void StartDownload()
    {
        var downloaderThread1 = new Downloader();
        var downloaderThread2 = new Downloader();
        var task1 = downloaderThread1.DownloadFileAsync(remoteAddress, downloadPath);
        var task2 = downloaderThread2.DownloadFileAsync(remoteAddress, downloadPath);
        Task.WaitAll();
    }

    class Downloader
    {           
        public async Task DownloadFileAsync(string remoteAddress, string downloadPath)
        {
            var client = new WebClient();
            client.DownloadProgressChanged += Client_DownloadProgressChanged;
            client.DownloadFileCompleted += Client_DownloadFileCompleted;
            await client.DownloadFileTaskAsync(remoteAddress, downloadPath);
        }
    }
}