对web服务的Post请求.错误:索引超出了数组的边界
本文关键字:索引 数组 边界 错误 服务 web Post 请求 | 更新日期: 2023-09-27 17:55:02
我有以下代码,用于从XML文件向web服务发送多个HTTP Post请求。这里的问题是,如果我把thread.Join()
放在注释的地方,我就能成功地放置所有请求。但是如果我对thread.Join()
使用第二个内部for循环,我得到
索引超出数组边界错误
thread[x] = new Thread(() => function(files[x],p));
in files[x]。这是主要的for循环。我不知道我哪里出错了。请纠正。我使用的是。net 4.0代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Xml;
using System.Net;
namespace ConsoleApplication4
{
class Program
{
int flag = 1;
string destination;
static void Main(string[] args)
{
int n = 0;
Program p = new Program();
Console.WriteLine("Enter the number");
string s = Console.ReadLine();
int.TryParse(s, out n);
Console.WriteLine("Enter Destination");
p.destination = Console.ReadLine();
string path = "D:''temp";
string[] files = null;
files = Directory.GetFiles(path, "*.xml", SearchOption.TopDirectoryOnly);
Thread[] thread = new Thread[files.Length];
int x;
int len = files.Length;
for (int i = 0; i<len; i+=n)
{
x = i;
for (int j = 0; j < n && x < len; j++)
{
thread[x] = new Thread(() => function(files[x],p));
thread[x].Start();
//thread[x].Join();
x++;
}
int y = x - n;
for (; y < x; y++)
{
int t = y;
thread[t].Join();
}
}
// thread[0] = new Thread(() => function(files[0]));
//thread[0].Start();
Console.ReadKey();
}
public static void function(string temp,Program p)
{
XmlDocument doc = new XmlDocument();
doc.Load(temp);
string final_d=p.destination + "response " + p.flag + ".xml";
p.flag++;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://10.76.22.135/wpaADws/ADService.asmx");
request.ContentType = "text/xml;charset='"utf-8'"";
request.Accept = "text/xml";
request.Method = "POST";
Stream stream = request.GetRequestStream();
doc.Save(stream);
stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
doc.LoadXml(soapResult);
File.WriteAllText(final_d, doc.DocumentElement.InnerText);
//XmlTextWriter xml=new XmlTextWriter(
Console.WriteLine(soapResult);
//Console.ReadKey();
}
}
}
}
这是因为表达式() => function(files[x],p)
在第一个内部循环完成后求值,并且x在该循环中递增。所以你总是得到x=len的超出范围的值。
要解决这个问题,需要声明另一个局部变量,并在匿名函数声明之前将x的值赋值给它,如下所示:
var localx=x;
thread[x] = new Thread(() => function(files[localx],p));
这里有一个链接,可以更深入地解释为什么会这样:有人能解释一下"访问修改过的闭包"吗?用简单的术语来描述c# ?