我正在使用SSH.NET从一个服务器到另一个服务器的SFTP文件。我使用的是C# .NET 4.5MVC 4,它的工作效果很好,除非有多个请求试图上传文件,这时我收到一个错误,即SSH私钥目前正被另一个进程使用。我假设一个请求设置了从私钥文件读取的ConnectionInfo对象,而另一个请求在从该文件读取第一个请求之前试图执行相同的操作。
有什么帮助吗?
注意,在下面的代码中,我将"test“添加到所有字符串obj值中。在生产中,情况并非如此。
谢谢!
public class SftpService : ISftpService
{
private static ConnectionInfo _sftpConnectionInfo { get; set; }
private static readonly string _mediaServerHost = "test";
private static readonly string _mediaServerUsername = "test";
private static readonly int _mediaServerPort = 22;
private static readonly string _privateSshKeyLocation = "test";
private static readonly string _privateSshKeyPhrase = "test";
private static readonly string _mediaServerUploadRootLocation = "test";
public SftpService()
{
var authenticationMethod = new PrivateKeyAuthenticationMethod(_mediaServerUsername, new PrivateKeyFile[]{
new PrivateKeyFile(_privateSshKeyLocation, _privateSshKeyPhrase)
});
// Setup Credentials and Server Information
_sftpConnectionInfo = new ConnectionInfo(_mediaServerHost, _mediaServerPort, _mediaServerUsername,
authenticationMethod
);
}
public void UploadResource(Stream fileStream)
{
using (var sftp = new SftpClient(_sftpConnectionInfo))
{
sftp.Connect();
//this is not the real path, just showing example
var path = "abc.txt";
sftp.UploadFile(fileStream, path, true);
sftp.Disconnect();
}
}
}
发布于 2016-05-05 10:23:32
简单地说,:你的假设是正确的。问题在于锁定和访问共享资源。
new PrivateKeyFile(_privateSshKeyLocation, _privateSshKeyPhrase)
您可以继续使用共享资源lock
来解决这个问题,同时尽量减少代码更改。一个潜在的起点将是SftpService()
。
继续创建父类的锁,并使用锁包装共享资源的内容:
private static object _lock = new object();
public SftpService()
{
lock (_lock)
{
// shared resources
}
}
https://stackoverflow.com/questions/33264858
复制相似问题