Reputation:
This is my sample code run under thread to download file from ftp server. In that, if the user want to stop file download, i tried to abort the thread. If the control in the while loop, its hang up.
How to close the binaryreader and Stream, when reader in the middle of stream
Using response As FtpWebResponse = CType(ftp.GetResponse, FtpWebResponse)
Using input As Stream = response.GetResponseStream()
Using reader As New BinaryReader(input)
Try
Using writer As New BinaryWriter(File.Open(targetFI.FullName, FileMode.Create)) 'output)
Dim buffer(2048) As Byte '= New Byte(2048)
Dim count As Integer = reader.Read(buffer, 0, buffer.Length)
While count <> 0
writer.Write(buffer, 0, count)
count = reader.Read(buffer, 0, buffer.Length)
End While
writer.Close()
End Using
Catch ex As Exception
'catch error and delete file only partially downloaded
targetFI.Delete()
'Throw
ret = False
End Try
reader.Close()
End Using
input.Close()
End Using
response.Close()
End Using
Upvotes: 0
Views: 1771
Reputation: 44919
You will need to add "polling" within your While
loop to check if a certain condition (in your case, the user wishes to abort the download) is true. If the condition is true, you can exit from the while loop.
For example, you will presumably have a function that is called when the user wishes to stop the download (this is perhaps in response to a Button click on a user interface or some such mechanism).
Using a class level boolean variable (or property), you can simply set this variable to true in response to the user wishing to abort the download, then within your while
loop that reads portions of the file from the FTP response stream, you check the value of this variable and if it's true
, you simply exit from the while
loop:
For example:
Somewhere at the class level, you declare:
Dim blnAbort as Boolean = False
When the user (for example) clicks a button to abort the download:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
blnAbort = True
End Sub
And in your main While Loop from the code in your question, you add:
While count <> 0
' Check the value of the blnAbort variable. If it is true, the user wants to abort, so we exit out of our while loop'
If blnAbort = True Then
Exit While
End If
writer.Write(buffer, 0, count)
count = reader.Read(buffer, 0, buffer.Length)
End While
This is the basic mechanism (polling) by which you should abort a long running process. Of course, you should always ensure that the relevant clean-up code is performed in the event of aborting (in your case, closing the reader and writer, which you are already doing). You may also need to make a call to Application.DoEvents
in your while
loop if this is being done in the context of a Windows Forms based application, and the user aborting is controlled by some king of GUI interaction. This will ensure that Windows messages generated by (for example) a button click are processed in a timely fashion.
Upvotes: 1