title: How to async / await in Renci.SshNet.BeginDownload with Task.Factory.FromAsync
body: <p>I have access to a Connected Renci.SshNet.SftpClient which I use to get a sequence of the files in the sftp folder. The function used for this is</p>
  
  <pre><code>Renci.SshNet.SftpClient.ListDirectory(string);
  </code></pre>
  
  <p>Due to the huge amount of files in the directory this takes about 7 seconds. I want to be able to keep my UI responsive using async / await and a cancellationToken.</p>
  
  <p>If Renci.SshNet had a ListDirectoryAsync function that returned a Task, then this would be easy:</p>
  
  <pre><code>async Task&lt;IEnumerable&lt;SftpFiles&gt; GetFiles(SftpClient connectedSftpClient, CancellationToken token)
  {
      var listTask connectedSftpClient.ListDirectoryAsync();
      while (!token.IsCancellatinRequested &amp;&amp; !listTask.IsCompleted)
      {
          listTask.Wait(TimeSpan.FromSeconds(0.2);
      }
      token.ThrowIfCancellationRequested();
      return await listTask;
  }
  </code></pre>
  
  <p>Alas the SftpClient doesn't have an async function. The following code works, however it doesn't cancel during the download:</p>
  
  <pre><code>public async Task&lt;IEnumerable&lt;SftpFile&gt;&gt; GetFilesAsync(string folderName, CancellationToken token)
  {
      token.ThrowIfCancellationRequested();
      return await Task.Run(() =&gt; GetFiles(folderName), token);
  }
  </code></pre>
  
  <p>However, the SftpClient does have kind of an async functionality using the functions</p>
  
  <pre><code>public IAsyncResult BeginListDirectory(string path, AsyncCallback asyncCallback, object state, Action&lt;int&gt; listCallback = null);
  Public IEnumerable&lt;SftpFile&gt; EndListDirectory(IAsyncResult asyncResult);
  </code></pre>
  
  <p>In the article <a href="https://www.justjuzzy.com/2012/10/turn-iasyncresult-code-into-await-keyword/" rel="nofollow">Turn IAsyncResult code into the new async and await Pattern</a> is described how to convert an IAsyncResult into an await.</p>
  
  <p>However I don't have a clue what to do with all the parameters in the BeginListdirectory and where to put the EndListDirectory. Anyone able to convert this into a Task on which I can wait with short timeouts to check the cancellation token?</p>