0

使用以下 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

谢谢你。

4

1 回答 1

0

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

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

如果你想取消你启动的第一个客户端,你需要在 click_handler 外部实例化它。

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

如果 client.IsBusy ...

于 2012-04-18T21:01:41.447 回答