3

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

Renci.SshNet.SftpClient.ListDirectory(string);

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.

If Renci.SshNet had a ListDirectoryAsync function that returned a Task, then this would be easy:

async Task<IEnumerable<SftpFiles> GetFiles(SftpClient connectedSftpClient, CancellationToken token)
{
    var listTask connectedSftpClient.ListDirectoryAsync();
    while (!token.IsCancellatinRequested && !listTask.IsCompleted)
    {
        listTask.Wait(TimeSpan.FromSeconds(0.2);
    }
    token.ThrowIfCancellationRequested();
    return await listTask;
}

Alas the SftpClient doesn't have an async function. The following code works, however it doesn't cancel during the download:

public async Task<IEnumerable<SftpFile>> GetFilesAsync(string folderName, CancellationToken token)
{
    token.ThrowIfCancellationRequested();
    return await Task.Run(() => GetFiles(folderName), token);
}

However, the SftpClient does have kind of an async functionality using the functions

public IAsyncResult BeginListDirectory(string path, AsyncCallback asyncCallback, object state, Action<int> listCallback = null);
Public IEnumerable<SftpFile> EndListDirectory(IAsyncResult asyncResult);

In the article Turn IAsyncResult code into the new async and await Pattern is described how to convert an IAsyncResult into an await.

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?

4

1 回答 1

5

看起来SftpClient它不遵循标准的APM 模式:它listCallback是 Begin 方法的一个额外参数。结果,我很确定您不能使用标准FromAsync工厂方法。

但是,您可以使用TaskCompletionSource<T>. 有点尴尬,但可行:

public static Task<IEnumerable<SftpFile>> ListDirectoryAsync(this SftpClient @this, string path)
{
  var tcs = new TaskCompletionSource<IEnumerable<SftpFile>>();
  @this.BeginListDirectory(path, asyncResult =>
  {
    try
    {
      tcs.TrySetResult(@this.EndListDirectory(asyncResult));
    }
    catch (OperationCanceledException)
    {
      tcs.TrySetCanceled();
    }
    catch (Exception ex)
    {
      tcs.TrySetException(ex);
    }
  }, null);
  return tcs.Task;
}

(用浏览器编写的代码,完全未经测试:)

我将其构建为扩展方法,这是我更喜欢的方法。这样,您的消费代码可以进行非常自然connectedSftpClient.ListDirectoryAsync(path)的调用。

于 2015-07-02T19:58:39.483 回答