简体   繁体   English

写入由 C# 中的 foreach 循环创建的 Task 内的文件

[英]Writing to files inside of a Task which is created by a foreach loop in C#

So I've come across an interesting issue.所以我遇到了一个有趣的问题。 I had to write a utility application that hits a webservice to pull down data and write it to a file.我必须编写一个实用程序应用程序来访问 web 服务以提取数据并将其写入文件。 The issue is that I have to make multiple concurrent calls to this webservice with different parameters and write the results to different files.问题是我必须使用不同的参数对该 Web 服务进行多次并发调用,并将结果写入不同的文件。 Here is the gist of it in pseudo-code...这是它在伪代码中的要点......

    var taskList = new List<Task>();
    foreach (string rCode in _config.rCodes) {
        taskList.Add(Task.Factory.StartNew(() =>
        {
            using (TextWriter tw = new StreamWriter(_config.OutputPath + string.Format(@"\{0}-{1}.csv", rCode, DateTime.Now.ToString("yyyy-MM-ddHHmmssfff")), false)) {
                <call webservice and write to the output file using tw.WriteLine>
            }
        }
    }
    Task.WaitAll(taskList.ToArray());

The tasks get created, webservices called, and data is getting written however I'm experiencing a collision of sorts.任务被创建,网络服务被调用,数据正在被写入,但是我遇到了各种各样的冲突。 I'm seeing data meant for one file ending up in another file.我看到用于一个文件的数据最终出现在另一个文件中。 I feel like each instance of the TextWriter in each created tasks are fighting with each other but in my mind, shouldn't they not because the scope of the TextWriter is the task that it was created in?我觉得每个创建的任务中 TextWriter 的每个实例都在相互争斗,但在我看来,它们不应该是因为 TextWriter 的范围是创建它的任务吗?

I did some researching and someone recommended doing a Parallel.Foreach but I experienced the same issue.我做了一些研究,有人建议做一个 Parallel.Foreach 但我遇到了同样的问题。 The reason I want to run these concurrently is that the result sets due to our third-party are required every 15 minutes and running in series instead of parallel could push that limit (affecting a public-facing application).我想同时运行这些的原因是由于我们第三方的结果集每 15 分钟需要一次并且串行而不是并行运行可能会推动该限制(影响面向公众的应用程序)。 Right now, we're OK but in the busier times of year, this could cause an issue when the data sets grow larger.现在,我们还好,但在一年中比较繁忙的时候,当数据集变大时,这可能会导致问题。

The problem is that rCode is in the outer scope, making it a global variable for sub-tasks.问题是rCode在外部范围内,使其成为子任务的全局变量。

To correct it, you can do:要纠正它,您可以执行以下操作:

foreach (string rCode in _config.rCodes)
{
    string code = rCode;
    taskList.Add(Task.Factory.StartNew(() =>
    {
        using (TextWriter tw = new StreamWriter(_config.OutputPath + string.Format(@"\{0}-{1}.csv", code, DateTime.Now.ToString("yyyy-MM-ddHHmmssfff")), false)) {
            // ...
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM