2012-04-04 92 views
0

使用以下VB.Net简单代码在FTP中上传文件时,对WebClient.CancelAsync()的调用实际上不会取消上载。使用WebClient取消上传?

有人知道为什么,以及可以做些什么呢?

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

我不使用VB自己,但它看起来像我在你错误的客户端上调用client.cancelAsync()。

您每次按下取消/上传按钮时都会创建一个新客户端。

如果您想取消您开始使用的第一个客户端,您需要将其外部实例化为click_handler。

此外,为什么你使用按钮标签来检查客户端是否应该被取消?

如果client.IsBusy ...

+0

我不知道你能做到的,我只是用Google搜索样本,发现上面。感谢您的信息,我会进行调查。 – Gulbahar 2012-04-19 14:35:11