5

我正在创建一个应用程序,它将

  1. 处理CSV文件,
  2. JObject为文件中的每条记录创建CSV并将 JSON 保存为 txt 文件,最后
  3. 将所有这些 JSON 文件上传到SFTP服务器

在为第三点寻找免费图书馆后,我决定使用SSH.NET.

我创建了以下类来异步执行上传操作。

public class JsonFtpClient : IJsonFtpClient
{
    private string _sfptServerIp, _sfptUsername, _sfptPassword;

    public JsonFtpClient(string sfptServerIp, string sfptUsername, string sfptPassword)
    {
        _sfptServerIp = sfptServerIp;
        _sfptUsername = sfptUsername;
        _sfptPassword = sfptPassword;
    }

    public Task<string> UploadDocumentAsync(string sourceFilePath, string destinationFilePath)
    {
        return Task.Run(() =>
        {
            using (var client = new SftpClient(_sfptServerIp, _sfptUsername, _sfptPassword))
            {
                client.Connect();

                using (Stream stream = File.OpenRead(sourceFilePath))
                {
                    client.UploadFile(stream, destinationFilePath);
                }

                client.Disconnect();
            }
            return (destinationFilePath);
        });
    }
}

UploadDocumentAsync方法返回一个TPL Task,以便我可以调用它来异步上传多个文件。

我从不同类中的以下方法调用此UploadDocumentAsync方法:

private async Task<int> ProcessJsonObjects(List<JObject> jsons)
{
    var uploadTasks = new List<Task>();
    foreach (JObject jsonObj in jsons)
    {
        var fileName = string.Format("{0}{1}", Guid.NewGuid(), ".txt");

        //save the file to a temp location
        FileHelper.SaveTextIntoFile(AppSettings.ProcessedJsonMainFolder, fileName, jsonObj.ToString());

        //call the FTP client class and store the Task in a collection
        var uploadTask = _ftpClient.UploadDocumentAsync(
                Path.Combine(AppSettings.ProcessedJsonMainFolder, fileName),
                string.Format("/Files/{0}", fileName));

        uploadTasks.Add(uploadTask);
    }

    //wait for all files to be uploaded
    await Task.WhenAll(uploadTasks);

    return jsons.Count();
}

尽管 CSV 文件会产生数千条 JSON 记录,但我想以至少 50 条为一组上传这些记录。这ProcessJsonObjects总是一次收到一个 50JObject秒的列表,我想将其异步上传到 SFTP 服务器。client.Connect();但是我在方法行收到以下错误UploadDocumentAsync

Session operation has timed out

将批量大小减少到 2 可以正常工作,但有时会导致以下错误:

Client not connected. 

我需要能够同时上传许多文件。或者告诉我 IIS 或 SFTP 服务器是否需要配置此类操作以及它是什么。

我究竟做错了什么?非常感谢您的帮助。

4

0 回答 0