vb.net多线程下载

Imports System.IO
Imports System.Net
Imports System.Threading

Public Class Form1
Private downloadThreads As List(Of Thread) = New List(Of Thread)()
Private downloadUrls As List(Of String) = New List(Of String)()

Private proxy As WebProxy = New WebProxy("http://proxy.example.com:8080")
Private threadCount As Integer = 10

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' 添加需要下载的网址
For i As Integer = 1 To 10000
downloadUrls.Add("http://example.com/file" & i & ".jpg")
Next
End Sub

Private Sub btnDownload_Click(sender As Object, e As EventArgs) Handles btnDownload.Click
' 计算每个线程需要下载的任务数
Dim taskCount As Integer = CInt(Math.Ceiling(downloadUrls.Count / CDbl(threadCount)))

' 创建多个线程进行下载
For i As Integer = 0 To threadCount - 1
Dim start As Integer = i * taskCount
Dim count As Integer = Math.Min(taskCount, downloadUrls.Count - start)

Dim t As Thread = New Thread(New ParameterizedThreadStart(AddressOf DownloadFiles))
downloadThreads.Add(t)
t.Start(New DownloadParams(start, count))
Next
End Sub

Private Sub DownloadFiles(downloadParams As Object)
Dim params As DownloadParams = CType(downloadParams, DownloadParams)

' 下载任务起始位置和任务数
Dim startIndex As Integer = params.StartIndex
Dim taskCount As Integer = params.TaskCount

' 创建WebClient对象
Dim myWebClient As WebClient = New WebClient()
myWebClient.Proxy = proxy

' 下载任务
For i As Integer = 0 To taskCount - 1
Dim index As Integer = startIndex + i
Dim remoteUri As String = downloadUrls(index)
Dim fileName As String = Path.GetFileName(remoteUri)

myWebClient.DownloadFile(remoteUri, fileName)
Next
End Sub

Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
' 等待所有线程结束
For Each t As Thread In downloadThreads
t.Join()
Next
End Sub

Private Class DownloadParams
Public Property StartIndex As Integer
Public Property TaskCount As Integer

Public Sub New(startIndex As Integer, taskCount As Integer)
Me.StartIndex = startIndex
Me.TaskCount = taskCount
End Sub
End Class
End Class



上一篇: vb.net多线程下载
下一篇: vb.net多线程下载
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: vb.net
相关日志:
评论: 0 | 引用: 0 | 查看次数: 314
发表评论
昵 称:
密 码: 游客发言不需要密码.
邮 箱: 邮件地址支持Gravatar头像,邮箱地址不会公开.
网 址: 输入网址便于回访.
内 容:
验证码:
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭

 广告位

↑返回顶部↑