C#WinSCP .NET程序集:如何异步上传多个文件

时间:2016-11-10 09:46:12

标签: c# asynchronous winscp winscp-net

我正在使用WinSCP .NET程序集上传文件。我想以异步方式上传多个文件。我已经创建了一个方法,但它可以作为单个上传工作。

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));
    }
}

请建议我正确的方法。感谢

2 个答案:

答案 0 :(得分:1)

您可以像这样使用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);
        }

答案 1 :(得分:1)

Session class的API只能在单个线程中使用。如果你从多个线程使用它,它将阻止。

因此,如果您需要并行传输,则必须为每个线程创建单独的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();
    }

    ...
}