I need some help getting the CancelTransfer method to work.
My GUI thread starts a new thread to do the actual transfer, which is wrapped in a class.
The method that starts the transfer contains:
public void BeginUpload()
{
ftpConn = new FTPConnection();
ftpConn.Connect();
ftpConn.UploadFile(_fileToUpload, _remoteFileName, false);
}
And the main GUI thread starts the Upload thread like so:
threadFTP = new System.Threading.Thread(ftpThread.BeginUpload);
threadFTP.Name = "FTPThread";
threadFTP.Start();
while (!threadFTP.Join(500))
{
if (this.bCancelled)
{
ftpThread.CancelUpload();
}
Application.DoEvents();
}
lblStatus3.Text = ""; //Line after thread.Join
All of the events work fine (BytesTransferred, Uploaded, Closed, etc) in the case of a completed transfer. the bCancelled variable is set when a user clicks the Cancel button on the form. I see that my class CancelUpload() method is called, but the application hangs on the ftpConn.Close() method. The thread.Join loop never ends and the application stops responding.
I call ftpConn.Close() rather than ftpConn.CancelTransfer because of the hints in the comments that Close() is preferred and will quit more gracefully:
[CancelTransfer] should not be used unless absolutely necessary. The server is not notified.
Sending true for abrubtClose doesn't help. What is the right way to cancel a transfer and get notified of that fact in the Uploaded event through e.Cancel?
If I call CancelTransfer() instead of Close(), the application does not hang and the Uploaded event fires immediately afterwards (with 200 MB left to go on the file being uploaded), but e.Cancel is false. Shouldn't it be true to indicate that the transfer was cancelled?
Here is the CancelUpload() method in the class that is running the separate upload thread:
public void CancelUpload()
{
if (ftpConn != null && ftpConn.IsConnected)
{
ftpConn.Close();
}
}