并行Webservice循环跳过

时间:2015-05-02 09:04:33

标签: c# web-services

我使用并行循环来调用web服务,因为循环的个体太慢了。然而,结果是跳过一些项目。

代码:

private void readCSV(string FilePath, string Extension)
{
    switch (Extension)
    {
        case ".csv":
            var reader = new StreamReader(File.OpenRead(FilePath));
            int counter = 0;
            List<int> phoneNo = new List<int>();

            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                phoneNo.Add(int.Parse(line));
            }
            reader.Close();

            Parallel.For(0, phoneNo.Count, (index) =>
            {
                counter++;
                Literal1.Text += counter + " " + phoneNo[index] + " " + webserviceClass123.callWebserviceMethod(phoneNo[index]) + "<br/>";
            });

            break;
    }
}

所以结果应该像(例子)

1 4189291 40.10
2 5124910 23.10
3 5123145 12.11
...
...
50 4124919 20.58

但是它出现了

3 8581892 41.10
1 9281989 10.99
50 4199289 02.22

它混乱了,它错过了很多数据

如何使其按顺序排列并确保所有数据都已表示?

1 个答案:

答案 0 :(得分:3)

一点也不清楚,您应该期望Literal1.Text += ...是线程安全的。我建议您使用Parallel.For循环 来收集数据,然后再更改Literal1.Text

例如,你可以写:

var results = new WhateverType[phoneNo.Count];
Parallel.For(0, phoneNo.Count,
    index => results[index] = webserviceClass123.callWebserviceMethod(phoneNo[index]));

var builder = new StringBuilder();
for (int i = 0; i < phoneNo.Count; i++)
{
    builder.AppendFormat("{0} {1} {2}<br/>",
        i, phoneNo[i], results[i]);
}
Literal1.Text = builder.ToString();

使用Parallel LINQ很可能更清晰:

var results = phoneNo
    .AsParallel()
    .Select(number => new { 
         number, 
         result = webserviceClass123.callWebserviceMethod(number)
    })
    .AsOrdered()
    .ToList()

var builder = new StringBuilder();
foreach (int i = 0; i < results.Count; i++)
{
    builder.AppendFormat("{0} {1} {2}<br/>",
        i, result[i].number, results[i].result);
}
Literal1.Text = builder.ToString();