一次发送多个帖子

本文关键字:一次 | 更新日期: 2023-09-27 18:33:15

我正在使用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一次发送多个帖子的方法是什么?

一次发送多个帖子

有多种方法,我经历过的最好的是波纹管:

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);
                }
            }
        });