我想在每個線程(每個線程1個XML數據文件)發送到Web服務器的多個XML文件。我似乎得到的問題是,它只發送一個文件,連接關閉,這意味着線程正在使用相同的連接流。我需要做什麼在我的try/catch代碼,以確保它爲每個線程創建一個新的連接,所以他們是獨立的連接,但我認爲即時通訊已經這樣做,但我不知道爲什麼它保持關閉連接,並沒有收到響應從網絡服務器,它只響應第一個XML線程,有時它響應所有。多線程的Web請求使用相同的連接
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
namespace XMLSender
{
class Program
{
private static string serverUrl;
static void Main(string[] args)
{
Console.WriteLine("Please enter the URL to send the XML File");
serverUrl = Console.ReadLine();
List<Thread> threads = new List<Thread>();
List<string> names = new List<string>();
string fileName = "";
do
{
Console.WriteLine("Please enter the XML File you Wish to send");
fileName = Console.ReadLine();
if (fileName != "start")
{
Thread t = new Thread(new ParameterizedThreadStart(send));
threads.Add(t);
names.Add(fileName);
}
}
while (fileName != "start");
foreach (Thread t in threads)
{
t.Start(names[0]);
names.RemoveAt(0);
}
foreach (Thread t in threads)
{
t.Join();
}
}
static private void send(object data)
{
try
{
//Set the connection limit of HTTP
System.Net.ServicePointManager.DefaultConnectionLimit = 10000;
//ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(serverUrl));
byte[] bytes;
//Load XML data from document
XmlDocument doc = new XmlDocument();
doc.Load((string)data);
string xmlcontents = doc.InnerXml;
//Send XML data to Webserver
bytes = Encoding.ASCII.GetBytes(xmlcontents);
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
// Get response from Webserver
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();
Console.Write(responseStr + Environment.NewLine);
}
catch (Exception e)
{
Console.WriteLine("An Error Occured" + Environment.NewLine + e);
Console.ReadLine();
}
}
}
}
然後調用「WebRequest.Create」創建一個新的連接... – 2016-08-02 13:21:52
[Parallel.For發送多個WebRequest]的可能的重複(http://stackoverflow.com/questions/7477261/send-multiple-webrequest- in-parallel-for) – Sinatr
它沒有嗎?在每個線程上運行的try catch部分?無論如何它不應該創建一個新的?但它沒有 – Freon