Vb.net 使用backgroundworker下载文件
我想使用backgroundworker下载两个zip文件,但当我想下载该文件时,会出现一个错误,即backgoundworker正忙,无法同时运行多个任务。这是密码Vb.net 使用backgroundworker下载文件,vb.net,backgroundworker,downloadfile,Vb.net,Backgroundworker,Downloadfile,我想使用backgroundworker下载两个zip文件,但当我想下载该文件时,会出现一个错误,即backgoundworker正忙,无法同时运行多个任务。这是密码 Imports System.Net Public Class mainForm Dim whereToSave As String 'Where the program save the file Private files() As String = {} Private dlCount As Integer = 0 Del
Imports System.Net
Public Class mainForm
Dim whereToSave As String 'Where the program save the file
Private files() As String = {}
Private dlCount As Integer = 0
Delegate Sub ChangeTextsSafe(ByVal length As Long, ByVal position As Integer, ByVal percent As Integer, ByVal speed As Double)
Delegate Sub DownloadCompleteSafe(ByVal cancelled As Boolean)
Public Sub DownloadComplete(ByVal cancelled As Boolean)
'Me.txtFileName.Enabled = True
Me.btnDownload.Enabled = True
Me.btnCancel.Enabled = False
If cancelled Then
Me.Label4.Text = "Cancelled"
MessageBox.Show("Download aborted", "Aborted", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
Me.Label4.Text = "Successfully downloaded"
MessageBox.Show("Successfully downloaded!", "All OK", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Me.ProgressBar1.Value = 0
'Me.Label5.Text = "Downloading: "
'Me.Label6.Text = "Save to: "
'Me.Label3.Text = "File size: "
'Me.Label2.Text = "Download speed: "
Me.Label4.Text = ""
End Sub
点击下载按钮
Private Sub btnDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDownload.Click
Me.btnDownload.Enabled = False
Me.btnCancel.Enabled = True
Dim TestString As String = "http://ec2-54-76-30-19.eu-west-1.compute.amazonaws.com/manapps/IDGo800_Minidriver_32.zip," & _
"http://ec2-54-76-30-19.eu-west-1.compute.amazonaws.com/manapps/IDGo800_Minidriver_64.zip"
Dim strFile As String
Dim length As Long
Dim position As Integer
Dim percent As Integer
Dim speed As Double
files = TestString.Split(CChar(","))
Dim a As String
For Each a In files
Dim b() As String = a.Split("/"c)
strFile = b(b.Length - 1)
'Dim strFileName As String = ""
'MsgBox(a)
'MsgBox(strFile)
Me.whereToSave = "C:\Temp\" & strFile
Me.DownloadingLabel.Text = "Downloading: " & strFile
Me.SaveToLabel.Text = "Save To: " & strFile
Me.FileSizeLabel.Text = "File Size: " & Math.Round((length / 1024), 2) & " KB"
Me.Label4.Text = "Downloaded " & Math.Round((position / 1024), 2) & " KB of " & Math.Round((length / 1024), 2) & "KB (" & Me.ProgressBar1.Value & "%)"
If speed = -1 Then
Me.DownloadSpeedLabel.Text = "Speed: calculating..."
Else
Me.DownloadSpeedLabel.Text = "Speed: " & Math.Round((speed / 1024), 2) & " KB/s"
End If
Me.ProgressBar1.Value = percent
dlCount = 0
StartDownload()
Next
End Sub
调用下载函数
Private Sub StartDownload()
dlCount += 1
If dlCount <= files.Length Then
BackgroundWorker1.RunWorkerAsync(files(dlCount - 1))
Else
MessageBox.Show("All files Downloaded")
'Button1.Enabled = True
End If
End Sub
如果完成,将调用backgroundcomplete
Private Sub bgw_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
StartDownload()
End Sub
您的代码看起来是正确的
添加此代码,然后重试
如果不是Me.BGWorkerTwo.IsBusy,那么Me.BGWorkerTwo.RunWorkerAsync()
对vb.net不是很好。但是为什么不使用任务呢。我认为他们更适合这样的行动
Sub Main()
Task.Factory.StartNew(Function() DownloadFile())
End Sub
Private Sub DownloadFile()
Dim webClient1 As New WebClient()
webClient1.DownloadFile("htt:\\one.two.three.com\file", "something.txt")
End Sub
所有文件都可以同时下载 导入系统.Net
公共类主窗体
Dim whereToSave As String 'Where the program save the file
Delegate Sub ChangeTextsSafe(ByVal length As Long, ByVal position As Integer, ByVal percent As Integer, ByVal speed As Double)
Delegate Sub DownloadCompleteSafe(ByVal cancelled As Boolean)
Public Sub DownloadComplete(ByVal cancelled As Boolean)
Me.txtFileName.Enabled = True
Me.btnDownload.Enabled = True
Me.btnCancel.Enabled = False
If cancelled Then
Me.Label4.Text = "Cancelled"
MessageBox.Show("Download aborted", "Aborted", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
Me.Label4.Text = "Successfully downloaded"
MessageBox.Show("Successfully downloaded!", "All OK", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Me.ProgressBar1.Value = 0
Me.Label5.Text = "Downloading: "
Me.Label6.Text = "Save to: "
Me.Label3.Text = "File size: "
Me.Label2.Text = "Download speed: "
Me.Label4.Text = ""
End Sub
Public Sub ChangeTexts(ByVal length As Long, ByVal position As Integer, ByVal percent As Integer, ByVal speed As Double)
Me.Label3.Text = "File Size: " & Math.Round((length / 1024), 2) & " KB"
Me.Label5.Text = "Downloading: " & Me.txtFileName.Text
Me.Label4.Text = "Downloaded " & Math.Round((position / 1024), 2) & " KB of " & Math.Round((length / 1024), 2) & "KB (" & Me.ProgressBar1.Value & "%)"
If speed = -1 Then
Me.Label2.Text = "Speed: calculating..."
Else
Me.Label2.Text = "Speed: " & Math.Round((speed / 1024), 2) & " KB/s"
End If
Me.ProgressBar1.Value = percent
End Sub
Private Sub btnDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDownload.Click
If Me.txtFileName.Text <> "" AndAlso Me.txtFileName.Text.StartsWith("http://") Then
Me.SaveFileDialog1.FileName = TextBox1.Text
If Me.SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Me.whereToSave = Me.SaveFileDialog1.FileName
Me.SaveFileDialog1.FileName = ""
Me.Label6.Text = "Save to: " & Me.whereToSave
Me.txtFileName.Enabled = False
Me.btnDownload.Enabled = False
Me.btnCancel.Enabled = True
Me.BackgroundWorker1.RunWorkerAsync() 'Start download
End If
Else
MessageBox.Show("Please insert valid URL for download", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
'Creating the request and getting the response
Dim theResponse As HttpWebResponse
Dim theRequest As HttpWebRequest
Try 'Checks if the file exist
theRequest = WebRequest.Create(Me.txtFileName.Text)
theResponse = theRequest.GetResponse
Catch ex As Exception
MessageBox.Show("An error occurred while downloading file. Possibe causes:" & ControlChars.CrLf & _
"1) File doesn't exist" & ControlChars.CrLf & _
"2) Remote server error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Dim cancelDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)
Me.Invoke(cancelDelegate, True)
Exit Sub
End Try
Dim length As Long = theResponse.ContentLength 'Size of the response (in bytes)
Dim safedelegate As New ChangeTextsSafe(AddressOf ChangeTexts)
Me.Invoke(safedelegate, length, 0, 0, 0) 'Invoke the TreadsafeDelegate
Dim writeStream As New IO.FileStream(Me.whereToSave, IO.FileMode.Create)
'Replacement for Stream.Position (webResponse stream doesn't support seek)
Dim nRead As Integer
'To calculate the download speed
Dim speedtimer As New Stopwatch
Dim currentspeed As Double = -1
Dim readings As Integer = 0
Do
If BackgroundWorker1.CancellationPending Then 'If user abort download
Exit Do
End If
speedtimer.Start()
Dim readBytes(4095) As Byte
Dim bytesread As Integer = theResponse.GetResponseStream.Read(readBytes, 0, 4096)
nRead += bytesread
Dim percent As Short = (nRead * 100) / length
Me.Invoke(safedelegate, length, nRead, percent, currentspeed)
If bytesread = 0 Then Exit Do
writeStream.Write(readBytes, 0, bytesread)
speedtimer.Stop()
readings += 1
If readings >= 5 Then 'For increase precision, the speed it's calculated only every five cicles
currentspeed = 20480 / (speedtimer.ElapsedMilliseconds / 1000)
speedtimer.Reset()
readings = 0
End If
Loop
'Close the streams
theResponse.GetResponseStream.Close()
writeStream.Close()
If Me.BackgroundWorker1.CancellationPending Then
IO.File.Delete(Me.whereToSave)
Dim cancelDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)
Me.Invoke(cancelDelegate, True)
Exit Sub
End If
Dim completeDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)
Me.Invoke(completeDelegate, False)
End Sub
Private Sub mainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.Label4.Text = ""
End Sub
Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
Me.BackgroundWorker1.CancelAsync() 'Send cancel request
End Sub
End Class
Dim whereToSave As String'程序保存文件的位置
代理子更改文本安全(ByVal长度为长,ByVal位置为整数,ByVal百分比为整数,ByVal速度为双精度)
委托子下载CompleteSafe(ByVal取消为布尔值)
公共子下载完成(ByVal取消为布尔值)
Me.txtFileName.Enabled=True
Me.btnDownload.Enabled=True
Me.btnCancel.Enabled=False
如果取消的话
Me.Label4.Text=“已取消”
显示(“下载中止”,“中止”,MessageBoxButtons.OK,MessageBoxIcon.Information)
其他的
Me.Label4.Text=“已成功下载”
Show(“已成功下载!”,“全部正常”,MessageBoxButtons.OK,MessageBoxIcon.Information)
如果结束
Me.ProgressBar1.Value=0
Me.Label5.Text=“正在下载:”
Me.Label6.Text=“保存到:”
Me.Label3.Text=“文件大小:”
Me.Label2.Text=“下载速度:”
Me.Label4.Text=“”
端接头
Public Sub ChangeTexts(ByVal长度为Long,ByVal位置为Integer,ByVal百分比为Integer,ByVal速度为Double)
Me.Label3.Text=“文件大小:”&Math.Round((长度/1024),2)和“KB”
Me.Label5.Text=“下载:”&Me.txtFileName.Text
Me.Label4.Text=“下载”&Math.Round((位置/1024),2)和“KB of”&Math.Round((长度/1024),2)和“KB(&Me.ProgressBar1.Value&%”)
如果速度=-1,则
Me.Label2.Text=“速度:计算…”
其他的
Me.Label2.Text=“速度:&&Math.Round((速度/1024),2)和“KB/s”
如果结束
Me.ProgressBar1.Value=百分比
端接头
私有子btnDownload_Click(ByVal发送方作为System.Object,ByVal e作为System.EventArgs)处理btnDownload。单击
如果Me.txtFileName.Text“”和Me.txtFileName.Text.StartWith(“http:/”),则
Me.SaveFileDialog1.FileName=TextBox1.Text
如果Me.SaveFileDialog1.ShowDialog=Windows.Forms.DialogResult.OK,则
Me.whereToSave=Me.SaveFileDialog1.FileName
Me.SaveFileDialog1.FileName=“”
Me.Label6.Text=“保存到:”&Me.whereToSave
Me.txtFileName.Enabled=False
Me.btnDownload.Enabled=False
Me.btnCancel.Enabled=真
Me.BackgroundWorker1.RunWorkerAsync()'开始下载
如果结束
其他的
显示(“请插入有效的下载URL”,“警告”,MessageBoxButtons.OK,MessageBoxIcon.Warning)
如果结束
端接头
私有子BackgroundWorker1_DoWork(ByVal sender作为System.Object,ByVal e作为System.ComponentModel.DoWorkEventTargets)处理BackgroundWorker1.DoWork
'创建请求并获取响应
将响应设置为HttpWebResponse
将请求设置为HttpWebRequest
Try'检查文件是否存在
theRequest=WebRequest.Create(Me.txtFileName.Text)
theResponse=theRequest.GetResponse
特例
MessageBox.Show(“下载文件时出错。可能原因:”&ControlChars.CrLf&_
“1)文件不存在”&ControlChars.CrLf&_
“2)远程服务器错误”,“错误”,MessageBoxButtons.OK,MessageBoxIcon.error)
Dim cancelDelegate作为新的DownloadCompleteSafe(DownloadComplete的地址)
Me.Invoke(cancelDelegate,True)
出口接头
结束尝试
Dim length As Long=响应的response.ContentLength大小(以字节为单位)
Dim safedelegate作为新变更文本安全(变更文本的地址)
调用(safedelegate,length,0,0,0)'调用安全委托
Dim writeStream作为新IO.FileStream(Me.whereToSave,IO.FileMode.Create)
'替换Stream.Position(webResponse Stream不支持seek)
作为整数的Dim nRead
'来计算下载速度
将速度计时器调暗为新秒表
变暗电流速度为双精度=-1
Dim读数为整数=0
做
如果BackgroundWorker1.CancellationPending,则“如果用户中止下载
退出Do
如果结束
speedtimer.Start()
Dim readBytes(4095)作为字节
Dim bytesread As Integer=响应.GetResponseStream.Read(读取字节,0,4096)
nRead+=字节读取
短尺寸百分比=(nRead*100)/长度
调用(safedelegate、长度、nRead、百分比、currentspeed)
如果bytesread=0,则退出Do
writeStream.Write(读取字节,0,字节读取)
speedtimer.Stop()
读数+=1
如果读数>=5,则为提高精度,仅每五圈计算一次速度
currentspeed=20480/(speedtimer.ElapsedMilliseconds/1000)
speedtimer.Reset()
读数=0
如果结束
环
"关河"
theResponse.GetResponseStream.Close()
writeStream.Close()
如果Me.BackgroundWorker1.CancellationPending,则
IO.File.Delete(Me.whereToSave)
Dim cancelDelegate作为新的DownloadCompleteSafe(DownloadComplete的地址)
Me.Invoke(cancelDelegate,True)
出口接头
如果结束
Dim completeDelegate作为新的下载完成安全(下载完成地址)
Me.Invoke(completeDelegate,False)
端接头
Private Sub mainForm_Load(ByVal sender作为System.Object,ByVal e作为System.EventArgs)处理MyBase.Load
Me.Label4.Text=“”
端接头
Dim whereToSave As String 'Where the program save the file
Delegate Sub ChangeTextsSafe(ByVal length As Long, ByVal position As Integer, ByVal percent As Integer, ByVal speed As Double)
Delegate Sub DownloadCompleteSafe(ByVal cancelled As Boolean)
Public Sub DownloadComplete(ByVal cancelled As Boolean)
Me.txtFileName.Enabled = True
Me.btnDownload.Enabled = True
Me.btnCancel.Enabled = False
If cancelled Then
Me.Label4.Text = "Cancelled"
MessageBox.Show("Download aborted", "Aborted", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
Me.Label4.Text = "Successfully downloaded"
MessageBox.Show("Successfully downloaded!", "All OK", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Me.ProgressBar1.Value = 0
Me.Label5.Text = "Downloading: "
Me.Label6.Text = "Save to: "
Me.Label3.Text = "File size: "
Me.Label2.Text = "Download speed: "
Me.Label4.Text = ""
End Sub
Public Sub ChangeTexts(ByVal length As Long, ByVal position As Integer, ByVal percent As Integer, ByVal speed As Double)
Me.Label3.Text = "File Size: " & Math.Round((length / 1024), 2) & " KB"
Me.Label5.Text = "Downloading: " & Me.txtFileName.Text
Me.Label4.Text = "Downloaded " & Math.Round((position / 1024), 2) & " KB of " & Math.Round((length / 1024), 2) & "KB (" & Me.ProgressBar1.Value & "%)"
If speed = -1 Then
Me.Label2.Text = "Speed: calculating..."
Else
Me.Label2.Text = "Speed: " & Math.Round((speed / 1024), 2) & " KB/s"
End If
Me.ProgressBar1.Value = percent
End Sub
Private Sub btnDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDownload.Click
If Me.txtFileName.Text <> "" AndAlso Me.txtFileName.Text.StartsWith("http://") Then
Me.SaveFileDialog1.FileName = TextBox1.Text
If Me.SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Me.whereToSave = Me.SaveFileDialog1.FileName
Me.SaveFileDialog1.FileName = ""
Me.Label6.Text = "Save to: " & Me.whereToSave
Me.txtFileName.Enabled = False
Me.btnDownload.Enabled = False
Me.btnCancel.Enabled = True
Me.BackgroundWorker1.RunWorkerAsync() 'Start download
End If
Else
MessageBox.Show("Please insert valid URL for download", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
'Creating the request and getting the response
Dim theResponse As HttpWebResponse
Dim theRequest As HttpWebRequest
Try 'Checks if the file exist
theRequest = WebRequest.Create(Me.txtFileName.Text)
theResponse = theRequest.GetResponse
Catch ex As Exception
MessageBox.Show("An error occurred while downloading file. Possibe causes:" & ControlChars.CrLf & _
"1) File doesn't exist" & ControlChars.CrLf & _
"2) Remote server error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Dim cancelDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)
Me.Invoke(cancelDelegate, True)
Exit Sub
End Try
Dim length As Long = theResponse.ContentLength 'Size of the response (in bytes)
Dim safedelegate As New ChangeTextsSafe(AddressOf ChangeTexts)
Me.Invoke(safedelegate, length, 0, 0, 0) 'Invoke the TreadsafeDelegate
Dim writeStream As New IO.FileStream(Me.whereToSave, IO.FileMode.Create)
'Replacement for Stream.Position (webResponse stream doesn't support seek)
Dim nRead As Integer
'To calculate the download speed
Dim speedtimer As New Stopwatch
Dim currentspeed As Double = -1
Dim readings As Integer = 0
Do
If BackgroundWorker1.CancellationPending Then 'If user abort download
Exit Do
End If
speedtimer.Start()
Dim readBytes(4095) As Byte
Dim bytesread As Integer = theResponse.GetResponseStream.Read(readBytes, 0, 4096)
nRead += bytesread
Dim percent As Short = (nRead * 100) / length
Me.Invoke(safedelegate, length, nRead, percent, currentspeed)
If bytesread = 0 Then Exit Do
writeStream.Write(readBytes, 0, bytesread)
speedtimer.Stop()
readings += 1
If readings >= 5 Then 'For increase precision, the speed it's calculated only every five cicles
currentspeed = 20480 / (speedtimer.ElapsedMilliseconds / 1000)
speedtimer.Reset()
readings = 0
End If
Loop
'Close the streams
theResponse.GetResponseStream.Close()
writeStream.Close()
If Me.BackgroundWorker1.CancellationPending Then
IO.File.Delete(Me.whereToSave)
Dim cancelDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)
Me.Invoke(cancelDelegate, True)
Exit Sub
End If
Dim completeDelegate As New DownloadCompleteSafe(AddressOf DownloadComplete)
Me.Invoke(completeDelegate, False)
End Sub
Private Sub mainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.Label4.Text = ""
End Sub
Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
Me.BackgroundWorker1.CancelAsync() 'Send cancel request
End Sub
End Class