session.SynchronizeDirectories can not be stopped if its started?

Advertisement

cyo
Joined:
Posts:
1
Location:
China

session.SynchronizeDirectories can not be stopped if its started?

I use Session.SynchronizeDirectories to download 1GB data from remote server via FTP. Once its started, by CancellationToken, I CANNOT stop it.

Can anyone check my code as below:
private CancellationTokenSource cancellationTokenSource;
 
public async Task Download(
    Session session, string TargetIP, string TargetPath, string DestiFolder,
    CancellationToken cancellationToken)
{
    Stopwatch sw = Stopwatch.StartNew();    
 
    try
    {
        // Setup session options
        SessionOptions sessionOptions = new SessionOptions
        {
            Protocol = Protocol.Ftp,
            HostName = TargetIP,
            UserName = "u1",
            Password = "p1",
            FtpMode = FtpMode.Passive,
            TimeoutInMilliseconds = 30000
        };
 
        session.FileTransferProgress += (sender, e) => SessionFileTransferProgress(sender, e, TargetIP);
        session.Open(sessionOptions);
 
        cancellationToken.ThrowIfCancellationRequested();
 
        TransferOptions transferOptions = new TransferOptions();
        transferOptions.TransferMode = TransferMode.Binary;
        transferOptions.ResumeSupport.State = TransferResumeSupportState.On;
 
        SynchronizationResult synchronizationResult;
        synchronizationResult =
            session.SynchronizeDirectories(
                SynchronizationMode.Local, DestiFolder, TargetPath, false);
 
        cancellationToken.ThrowIfCancellationRequested();
 
        synchronizationResult.Check();
 
        sw.Stop();
 
        session.Close();
        return;
    }
    catch (OperationCanceledException)
    {
        session.Close();                    
        session.Dispose();
        session.Abort();
        throw;
    }
    catch (Exception e)
    {
        Debug.WriteLine($"Error: {e}");
        session.Dispose();
    }
}
 
private void button11_Click(object sender, EventArgs e)
{
    cancellationTokenSource.Cancel();
}
The issue is once downloading is started, it can not be stopped. I can only close my C# application to stop it.

Can anyone help? Thanks

Reply with quote

Advertisement

A9G-Data-Droid
A9G-Data-Droid avatar
Joined:
Posts:
5
Location:
Space

Re: session.SynchronizeDirectories can not be stopped if its started?

The simple way to do this in C# would be to register with the token like this:
cancellationToken.Register(session.Abort);
However the session.Abort doc https://winscp.net/eng/docs/library_session_abort says
To cancel a file transfer, use FileTransferProgressEventArgs.Cancel instead.
I'm not sure how to get the token from the place where the download begins all the way to the event handler because that is coming in on a different thread.

Reply with quote

Advertisement

You can post new topics in this forum