同时从S3读取文件

时间:2018-09-26 06:38:02

标签: c# multithreading amazon-s3

我正在调用以下方法从S3获取文件。我有一个集合中的文件路径列表。我在Parallel.Foreach循环中调用以下方法。容器的方法addRecords()是线程安全的,并确保只有一个线程进入临界区。该代码跳过了一些文件,返回的结果记录少于预期。

Parallel.ForEach(fileListAll, new ParallelOptions { MaxDegreeOfParallelism = 20 }, (currentFile) =>
                {
                    string RecordsRaw = _AmazonS3.GetFileFromS3(currentFile);

                    Container.AddRecords(RecordsRaw);
                });



public string GetFileFromS3(string filePath)
        {
            try
            {
                string ResponseData = null;
                GetObjectRequest Request = new GetObjectRequest
                {
                    BucketName = _AWSConfiguration.S3BucketName,
                    Key = filePath
                };
                using (GetObjectResponse response = _AmazonS3Client.GetObject(Request))
                using (Stream responseStream = response.ResponseStream)
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    ResponseData = reader.ReadToEnd();
                }
                if (!string.IsNullOrEmpty(ResponseData))
                {
                    return ResponseData;
                }
            }
            catch (Exception ex)
            {
                //Removed the code for brevity
            }
            return null;
        }

我不确定如何更改GetFileFromS3()方法,以便可以由多个线程调用该方法,同时仍保持并发性。

请耐心等待,因为这可能是一个基本问题,但是我要花2天的时间才能使其正常工作。

0 个答案:

没有答案