一次发送多个帖子

时间:2016-02-03 19:37:49

标签: c# asp.net httpwebrequest

我正在使用SQL查询从我的数据库中选择数据并将返回的结果存储在Dictionary<string, string>我然后使用foreach循环和Server.UrlEncode来创建Querystring像这样的

foreach (var onetwo in privatedictionary) 
    dataToPost = onetwo.Key+"="+Server.UrlEncode(onetwo.Value)+"&";

然后将数据编译成dataToPost后,我使用HttpWebRequest发送数据

HttpWebRequest wbrq = (HttpWebRequest)WebRequest.Create("www.sitetohit.com");
{
  using (StreamWriter sw = new StreamWriter(wbrq.GetRequestStream()))
  {
    sw.Write(dataToPost);
  }
}

使用Visual Studio 2015一次发送多个帖子的方法是什么?

1 个答案:

答案 0 :(得分:1)

有多种方式,我所经历的最好的方式是:

Parallel.ForEach(privatedictionary, (dataToPost) =>
        {
            HttpWebRequest wbrq = (HttpWebRequest)WebRequest.Create("www.sitetohit.com");
            {
                using (StreamWriter sw = new StreamWriter(wbrq.GetRequestStream()))
                {
                    sw.Write(dataToPost);
                }
            }
        });

或者:

foreach (var dataToPost in privatedictionary)
        {
            Task.Run(async () =>
            {
                Foo foo = new Foo();
                await foo.BarAsync(dataToPost);
            });
        }

  //Asynchronous Handling
  public class Foo
{
    public async Task BarAsync(string dataToPost)
    {
        HttpWebRequest wbrq = (HttpWebRequest)WebRequest.Create("www.sitetohit.com");
        {
            using (StreamWriter sw = new StreamWriter(wbrq.GetRequestStream()))
            {
                await sw.WriteAsync(dataToPost);
            }
        }
    }
}

您可以使用:

Parallel.ForEach(privatedictionary, (onetwo) =>
        {
            var dataToPost = onetwo.Key + "=" + Server.UrlEncode(onetwo.Value) + "&";
            HttpWebRequest wbrq = (HttpWebRequest)WebRequest.Create("www.sitetohit.com");
            {
                using (StreamWriter sw = new StreamWriter(wbrq.GetRequestStream()))
                {
                    sw.Write(dataToPost);
                }
            }
        });