2016-02-03 42 views
0

我使用一个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送MUL方式tiple帖子一次?

+0

你可以使用线程并行操作。 –

+0

@TeodorIvanov - 我将在“Parallel.For”中添加哪个部分?我的字典一次只能保存一个值,那么我需要创建多个字典吗?或者可以计算出SQL查询可能返回多少条可能的记录,并在该概念上使用'Parallel.For'? – RashidInman

回答

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

字典不能有重复值如何克服,以便我可以从我的数据库返回多个结果集? – RashidInman

+0

您可以遍历字典并在循环体内构建** dataToPost **。 –

+0

也许我无法理解你想要传达给我的东西,我所看到的只是如果字典在时间只能保持1个值,我不能循环1的值... – RashidInman