我正在尝试使用 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<Task>();
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();
}
Because 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<Task>();
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);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)