asp.net 4.5

Уже много хорошего было сказано про следующую версию asp.net , которая выйдет вместе с windows server 8.
Для тех кто пропустил. Вот видео про минимизацию и заметное ускорение открытия страниц. И вот еще общая концепция улучшений. Можно видеть, что большой упор сделан на асинхронные операции. В частности по получению ответов из WebResponse. Сейчас же приходится использовать много второстепенного кода для реализации асинхронного сичтывания. Ниже приведу фрагмент, который используется для асинхронной обработки ответов получаемых из ЖЖ. После нескольких ДДОС атак они стали параноидальными и включили в ответах chuncked, чтобы контролировать загруженность канала, поэтому синхронное считывание очень часто проваливается. Выход из этой проблемы реализуется следующим классом, который надеюсь станет неактуальным в 4.5:
Copy Source | Copy HTML
  1. #region Ассинхронное чтение из документации
  2.     public class RequestState
  3.     {
  4.         // This class stores the State of the request.
  5.         const int BUFFER_SIZE = 1024 * 256;
  6.         public StringBuilder requestData;
  7.         public byte[] BufferRead;
  8.         public HttpWebRequest request;
  9.         public HttpWebResponse response;
  10.         public Stream streamResponse;
  11.         public Encoding encoding;
  12.         public FileStream FileToWrite;
  13.         public RequestState()
  14.         {
  15.             BufferRead = new byte[BUFFER_SIZE];
  16.             requestData = new StringBuilder("");
  17.             request = null;
  18.             streamResponse = null;
  19.             encoding = Encoding.UTF8;
  20.             FileToWrite = null;
  21.         }
  22.     }
  23.  
  24.     class HttpWebRequest_BeginGetResponse
  25.     {
  26.         public ManualResetEvent allDone;
  27.         const int BUFFER_SIZE = 1024 * 256;
  28.         const int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout
  29.  
  30.         // Abort the request if the timer fires.
  31.         private static void TimeoutCallback(object state, bool timedOut)
  32.         {
  33.             if (timedOut)
  34.             {
  35.                 HttpWebRequest request = state as HttpWebRequest;
  36.                 if (request != null)
  37.                 {
  38.                     request.Abort();
  39.                 }
  40.             }
  41.         }
  42.  
  43.         public RequestState ReadAsyncWebResp(HttpWebRequest myHttpWebRequest, string filepath)
  44.         {
  45.             // Create an instance of the RequestState and assign the previous myHttpWebRequest
  46.             // object to its request field.  
  47.             RequestState myRequestState = new RequestState();
  48.             allDone = new ManualResetEvent(false);
  49.             myRequestState.request = myHttpWebRequest;
  50.             //Open a file to write if needed
  51.             if (!String.IsNullOrEmpty(filepath))
  52.             {
  53.                 myRequestState.FileToWrite = File.Open(filepath, FileMode.OpenOrCreate);
  54.             }
  55.  
  56.             // Start the asynchronous request.
  57.             IAsyncResult result =
  58.               myHttpWebRequest.BeginGetResponse(RespCallback, myRequestState);
  59.  
  60.             // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
  61.             ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, myHttpWebRequest, DefaultTimeout, true);
  62.  
  63.             // The response came in the allowed time. The work processing will happen in the 
  64.             // callback function.
  65.             allDone.WaitOne();
  66.  
  67.             // Release the HttpWebResponse resource.
  68.             myRequestState.response.Close();
  69.             if (myRequestState.FileToWrite != null)
  70.             {
  71.                 myRequestState.FileToWrite.Close();
  72.             }
  73.             allDone.Close();
  74.             return myRequestState;
  75.         }
  76.  
  77.         private void RespCallback(IAsyncResult asynchronousResult)
  78.         {
  79.             try
  80.             {
  81.                 // State of request is asynchronous.
  82.                 RequestState myRequestState = (RequestState)asynchronousResult.AsyncState;
  83.                 HttpWebRequest myHttpWebRequest = myRequestState.request;
  84.                 myRequestState.response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(asynchronousResult);
  85.  
  86.                 // Read the response into a Stream object.
  87.                 Stream responseStream = myRequestState.response.GetResponseStream();
  88.                 myRequestState.streamResponse = responseStream;
  89.  
  90.                 // Begin the Reading of the contents of the HTML page and print it to the console.
  91.                 IAsyncResult asynchronousInputRead = responseStream.BeginRead(myRequestState.BufferRead,  0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
  92.                 return;
  93.             }
  94.             catch (WebException e)
  95.             {
  96.             }
  97.             allDone.Set();
  98.         }
  99.         private void ReadCallBack(IAsyncResult asyncResult)
  100.         {
  101.             try
  102.             {
  103.  
  104.                 RequestState myRequestState = (RequestState)asyncResult.AsyncState;
  105.                 Stream responseStream = myRequestState.streamResponse;
  106.                 int read = responseStream.EndRead(asyncResult);
  107.                 // Read the HTML page and then print it to the console.
  108.                 if (read >  0)
  109.                 {
  110.                     if (myRequestState.FileToWrite != null)
  111.                     {
  112.                         myRequestState.FileToWrite.Write(myRequestState.BufferRead,  0, read);
  113.                     }
  114.                     myRequestState.requestData.Append(myRequestState.encoding.GetString(myRequestState.BufferRead,  0, read));
  115.                     IAsyncResult asynchronousResult = responseStream.BeginRead(myRequestState.BufferRead,  0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
  116.                     return;
  117.                 }
  118.                 else
  119.                 {
  120.                     responseStream.Close();
  121.                 }
  122.  
  123.             }
  124.             catch (WebException e)
  125.             {
  126.             }
  127.             catch (IOException eio)
  128.             {
  129.             }
  130.             //пофиг на ошибки. что скачалось, то скачалось
  131.             allDone.Set();
  132.         }
  133.     }
  134.     #endregion

Метки: Code


Добавить комментарий



biuquote
Loading


Кто я?

Программист. Я слежу за блогосферой и знаю, как будет развиваться интернет. Когда у меня есть время я даже прилагаю для этого усилия. Подробнее

Последние комментарии

Topbot at FeedsBurner