使用以下VB.Net简单代码在FTP上传文件,调用WebClient.CancelAsync()实际上不会取消上传。
有人知道为什么,可以做些什么呢?
Private Sub UploadProgressChanged(ByVal sender As Object, ByVal e As System.Net.UploadProgressChangedEventArgs)
'TO-DO: Why is pbar empty?
ProgressBar1.Value = e.ProgressPercentage
Label1.Text = e.BytesSent & " bytes sent"
End Sub
Private Sub UploadFileCompleted(ByVal sender As Object, ByVal e As System.Net.UploadFileCompletedEventArgs)
MessageBox.Show("Done!")
Button1.Text = "Upload"
ProgressBar1.Value = 0
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim client As New WebClient
If Button1.Text = "Cancel" Then
'TO-DO: Doesn't actually cancel upload!
client.CancelAsync()
Button1.Text = "Upload"
ProgressBar1.Value = 0
Else
Button1.Text = "Cancel"
Const MYFILE = "big.file.bin"
Const LocalFile As String = "C:\" & MYFILE
Dim RemoteFile As String = "ftp://upload.acme.com/" & MYFILE
client.Credentials = New NetworkCredential("anonymous", "test")
client.Proxy = Nothing
AddHandler client.UploadFileCompleted, AddressOf UploadFileCompleted
AddHandler client.UploadProgressChanged, AddressOf UploadProgressChanged
ProgressBar1.Maximum = 100
Try
client.UploadFileAsync(New Uri(RemoteFile), LocalFile)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
client.Dispose()
End If
End Sub
谢谢。
答案 0 :(得分:0)
我自己不使用VB,但它看起来像是在错误的客户端上调用client.cancelAsync()。
每次按取消/上传按钮时,您都会创建一个新客户端。
如果要取消启动的第一个客户端,则需要在click_handler外部实例化它。
另外,为什么使用按钮标签检查是否应取消客户端?
如果是client.IsBusy ......
,你可以这样做