This project is read-only.

SFTP Async Upload in Parallel

Aug 21, 2012 at 3:28 PM


I'm new at the SSH.NET library  and want to upload asyncronulsy in a site using the parallel function in .net4.0. Is there an example that I can folow ?



Aug 23, 2012 at 7:51 PM
Edited Aug 24, 2012 at 9:39 PM

Hi there

I am successfully doing this, but am using .net 4.5 and c# 5.0, using the new async stuff.

At the lowest level I have a method that can "put" a file to a remote system:

      public Task<String> PutFileAsync(string remoteFilepath, string localFilepath) {
            // Upload file localFilepath to remoteFilepath and returns remoteFilepath
            // It is safe to run this code concurrently

            return (Task.Run(() => {
                using (var client = new SftpClient(IPAddress, _SSHUserName, new PrivateKeyFile(File.OpenRead(_SSHLocalPrivateKeyFilepath)))) {
                    using (Stream stream = File.OpenRead(localFilepath)) {
                        client.UploadFile(stream, remoteFilepath);
                return (remoteFilepath);


To issue multiple calls concurrently, you can do something like this:


Task<String> task1 = PutFileAsync(remoteFilepath, localFilepath);
Task<String> task2 = PutFileAsync(remoteFilepath, localFilepath);
Task<String> task3 = PutFileAsync(remoteFilepath, localFilepath);

await Task.WhenAll(task1, task2, task3)


The first three calls to PutFileAsync all start a call to ssh on a threadpool thread and return a task. These tasks are running at the "same time". I asynchronously wait for them all to finish in the final line, with "await".

I believe this example can be easily adapted to use in the TPL; you'd still be creating multiple tasks (one for each SSH operation) and would still need a way to wait on them, possible with something like WaitAll, which I think is also part of the Task assembly.

Hope this helps