C# 同时发布多个HttpWebRequest
我正在尝试将POST请求发送到web服务器,它们必须同时完成。C# 同时发布多个HttpWebRequest,c#,parallel-processing,httpwebrequest,C#,Parallel Processing,Httpwebrequest,我正在尝试将POST请求发送到web服务器,它们必须同时完成。我编写了下面的代码,但它每秒发送4个请求。例如,如果我想发送20个POST请求,大约需要6秒钟,而且它们不会像我希望的那样同时发送。 我已尝试将ServicePointManager.DefaultConnectionLimit和ServicePointManager.MaxServicePoints设置得更高,但仍然相同 class BrowserAsync { private HttpWebRequest WebReq;
我编写了下面的代码,但它每秒发送4个请求。例如,如果我想发送20个POST请求,大约需要6秒钟,而且它们不会像我希望的那样同时发送。
我已尝试将ServicePointManager.DefaultConnectionLimit和ServicePointManager.MaxServicePoints设置得更高,但仍然相同
class BrowserAsync
{
private HttpWebRequest WebReq;
public void makePOST(string url, string POST)
{
byte[] buffer = Encoding.ASCII.GetBytes(POST);
WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.Headers.Clear();
// CUSTOM HEADERS HERE -- not shown in this example
WebReq.KeepAlive = false;
WebReq.Proxy = null;
WebReq.Method = "POST";
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;
Stream PostData = WebReq.GetRequestStream();
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
WebReq.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);
}
private void FinishWebRequest(IAsyncResult result)
{
// data returned is not important, just end it
WebReq.EndGetResponse(result);
}
}
每个实例都从其自己的线程调用:
public static void waitAndExecute(object threadInfo)
{
// this is the thread on it's own
ThreadInformation info;
info = (ThreadInformation)threadInfo;
// WAIT
// Display("Sleeping until " + DateTime.Now.AddMilliseconds((info.exTime - DateTime.Now).TotalMilliseconds - info.ping)
// the same sleeping time is displayed for all threads
System.Threading.Thread.Sleep((int)(info.exTime - DateTime.Now).TotalMilliseconds - info.ping);
BrowserAsync brw = new BrowserAsync();
brw.makePOST("url", info.postParameters);
}
您可以使用
HttpClient
和PostAsync
您可以使用StringContent
类传递第二个参数HttpContent,例如
var client = new HttpClient();
client.PostAsync(url, new StringContent(POST));
请参见此处,以获取一个同时启动所有请求的示例,但使用
GetAsync
您的问题是什么?你有错误吗?你期望的结果是什么?你得到了什么结果?我想同时发送20个帖子。我没有收到任何错误。结果是前4个帖子在1秒内发送,其他4个帖子在2秒内发送,等等……您使用什么代码调用waitAndExecute方法20次?还有什么设置信息的exTime和ping属性呢?这是一个漫长而复杂的方法。所有20个线程的exTime和ping属性都相同。它们是由那个方法设置的(“长而复杂”)。一个长而复杂的方法,可能需要0.25秒来启动每个线程?