SSH.Net异步文件下载

我试图使用SSH.NET从SFTP服务器异步下载文件。 如果我同步执行它,它工作正常,但当我执行异步时,我得到空文件。 这是我的代码:

var port = 22; string host = "localhost"; string username = "user"; string password = "password"; string localPath = @"C:\temp"; using (var client = new SftpClient(host, port, username, password)) { client.Connect(); var files = client.ListDirectory(""); var tasks = new List(); foreach (var file in files) { using (var saveFile = File.OpenWrite(localPath + "\\" + file.Name)) { //sftp.DownloadFile(file.FullName,saveFile); <-- This works fine tasks.Add(Task.Factory.FromAsync(client.BeginDownloadFile(file.FullName, saveFile), client.EndDownloadFile)); } } await Task.WhenAll(tasks); client.Disconnect(); } 

因为saveFile是在using块中声明的,所以在启动任务后它立即关闭,因此无法完成下载。 实际上,我很惊讶你没有得到例外。

您可以提取代码以下载到单独的方法,如下所示:

 var port = 22; string host = "localhost"; string username = "user"; string password = "password"; string localPath = @"C:\temp"; using (var client = new SftpClient(host, port, username, password)) { client.Connect(); var files = client.ListDirectory(""); var tasks = new List(); foreach (var file in files) { tasks.Add(DownloadFileAsync(file.FullName, localPath + "\\" + file.Name)); } await Task.WhenAll(tasks); client.Disconnect(); } ... async Task DownloadFileAsync(string source, string destination) { using (var saveFile = File.OpenWrite(destination)) { var task = Task.Factory.FromAsync(client.BeginDownloadFile(source, saveFile), client.EndDownloadFile); await task; } } 

这样,在下载文件之前,文件不会关闭。


看看SSH.NET源代码,看起来像DownloadFile的异步版本没有使用“真正的”异步IO(使用IO完成端口),而只是在新线程中执行下载。 因此使用BeginDownloadFile / EndDownloadFile没有任何优势; 您也可以在自己创建的主题中使用DownloadFile

 Task DownloadFileAsync(string source, string destination) { return Task.Run(() => { using (var saveFile = File.OpenWrite(destination)) { client.DownloadFile(source, saveFile); } } }