[英]C# WinSCP .NET assembly: How to upload multiple files asynchronously
I am using WinSCP .NET assembly for uploading files.我正在使用 WinSCP .NET 程序集上传文件。 I want to upload multiple files asynchronous way.
我想以异步方式上传多个文件。 I have created a method but it works as single upload.
我创建了一个方法,但它可以作为单个上传。
public class UploadingData {
private SessionOptions _sessionOptions;
private Session _session;
//connection etc
private void OnConnected() {
foreach (var fileInfo in localFilesList)
{
var task = Task.Factory.StartNew(() => UploadFilesAsync(fileInfo));
}
}
private async Task UploadFilesAsync(string file) {
string remoteFilePath = _session.TranslateLocalPathToRemote(file, @"/", "/test_data_upload");
var uploading = _session.PutFiles(file, remoteFilePath, false);
//When Done
await Task.Run(() => Thread.Sleep(1000));
}
}
Please suggest me correct way.请建议我正确的方法。 Thanks
谢谢
The API of the Session
class can be used from a single thread only. Session
类的 API 只能在单个线程中使用。 If you use it from multiple threads, it will block.如果从多个线程使用它,它将阻塞。
So if you need parallel transfers, you have to create a separate Session
instance for each thread.因此,如果您需要并行传输,则必须为每个线程创建一个单独的
Session
实例。
private async Task UploadFilesAsync(string file)
{
using (Session session = new Session())
{
session.Open(_sessionOptions);
string remoteFilePath =
RemotePath.TranslateLocalPathToRemote(file, @"/", "/test_data_upload");
session.PutFiles(file, remoteFilePath, false).Check();
}
...
}
See also WinSCP article Automating transfers in parallel connections over SFTP/FTP protocol with code examples for C# and PowerShell.另请参阅 WinSCP 文章 通过 SFTP/FTP 协议在并行连接中自动传输以及 C# 和 PowerShell 的代码示例。
Note that you should not use more than few sessions/threads (about 4).请注意,您不应使用超过几个会话/线程(大约 4 个)。 With more sessions, you will hardly get better throughput.
随着会话数的增加,您将很难获得更好的吞吐量。
You can use BackgroundWorker class like this:您可以像这样使用 BackgroundWorker 类:
string[] images = new string[50];
foreach (var path in images)
{
BackgroundWorker w = new BackgroundWorker();
//50 independently async Threads
w.DoWork += delegate (object s, DoWorkEventArgs args)
{
Upload(args.Argument.ToString());
};
w.RunWorkerAsync(path);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.