.NET 4.x Многопоточная отправка запросов - C#

Узнай цену своей работы

Формулировка задачи:

Народ подскажите как реализовать многопоточную отправку запросов) Вот код
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.Net;
  10. using System.IO;
  11. using System.Threading;
  12. namespace WindowsFormsApplication1
  13. {
  14. public partial class Form1 : Form
  15. {
  16. public Form1()
  17. {
  18. InitializeComponent();
  19. }
  20. private void button1_Click(object sender, EventArgs e)
  21. {
  22. Thread[] threads = new Thread[10];
  23. for (int i = 0; i < 10; i++)
  24. {
  25. Thread t = new Thread(new ThreadStart(DoTransactions));
  26. threads[i] = t;
  27. }
  28. for (int i = 0; i < 10; i++)
  29. {
  30. threads[i].Start();
  31. }
  32. }
  33. string strNewValue;
  34. string strResponse;
  35. int zzz = 0;
  36. public void DoTransactions()
  37. {
  38.  
  39. string[] ID = "".Split();
  40. richTextBox1.Invoke(new EventHandler(delegate { ID = richTextBox1.Text.Split('\n'); }));
  41. string[] Auth_ID;
  42. string ids = "555";
  43.  
  44. lock (this)
  45. {
  46. for (int i = 0; i < ID.Length; i++)
  47. {
  48. Auth_ID = ID[i].Split(':');
  49. HttpWebRequest req = (HttpWebRequest)WebRequest.Create("........");
  50. req.Proxy = new WebProxy("127.0.0.1", 8888);
  51. // Set values for the request back
  52. req.Method = "POST";
  53. req.ContentType = "application/x-www-form-urlencoded";
  54. strNewValue = "...."+Auth_ID[0]+"....."+Auth_ID[1];
  55. req.ContentLength = strNewValue.Length;
  56. // Write the request
  57. StreamWriter stOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
  58. stOut.Write(strNewValue);
  59. stOut.Close();
  60. // Do the request to get the response
  61. StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
  62. strResponse = stIn.ReadToEnd();
  63. stIn.Close();
  64. }
  65. }
  66. }
  67.  
  68. }
  69. }
все равно медленно...(((

Решение задачи: «.NET 4.x Многопоточная отправка запросов»

textual
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Runtime.Remoting.Messaging;
  7. using System.Text;
  8. using System.Threading;
  9.  
  10. namespace ConsoleApplicationTest {
  11.     static class Program {
  12.         static void Main( string[] args ) {
  13.             var urls = new[] {
  14.                 "http://wikipedia.org",
  15.                 "http://msdn.microsoft.com",
  16.                 "http://www.cyberforum.ru"
  17.             };
  18.  
  19.             // Состояния асинхронных операций.
  20.             var asyncResults = new List<IAsyncResult>();
  21.  
  22.             foreach ( string uri in urls ) {
  23.                 HttpWebRequest req = (HttpWebRequest)WebRequest.Create( uri );
  24.                 var asyncResult = req.BeginGetResponse( null, req );
  25.                 Console.WriteLine( "Запрос отправлен на " + uri );
  26.                 asyncResults.Add( asyncResult );
  27.                
  28.             }
  29.  
  30.             // Ждём завершения всех запросов.
  31.             WaitHandle.WaitAll( asyncResults.Select(result => result.AsyncWaitHandle).ToArray() );
  32.  
  33.             // Получаем ответы
  34.             var responses = new List<string>();
  35.             foreach ( IAsyncResult asyncResult in asyncResults ) {
  36.                 HttpWebRequest request = (HttpWebRequest) asyncResult.AsyncState;
  37.  
  38.                 using ( var response = request.EndGetResponse( asyncResult ) ) {
  39.                     using ( var reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII ) ) {
  40.                         responses.Add( reader.ReadToEnd() );
  41.                     }
  42.                 }
  43.                 asyncResult.AsyncWaitHandle.Close();
  44.                 Console.WriteLine( "Ответ получен от "+ request.RequestUri );
  45.             }
  46.  
  47.             foreach ( string response in responses ) {
  48.                 Console.WriteLine( response );
  49.             }
  50.  
  51.             Console.ReadKey();
  52.         }
  53.     }
  54. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

12   голосов , оценка 4.417 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы