// Thread to handle HTTP requests private void WorkerThread( ) { while (!stopEvent.WaitOne(0, false)) { HttpCommand commandToProcess = null; commandEvent.WaitOne( ); lock ( sync ) { if (commandQueue.Count != 0) { commandToProcess = commandQueue[0]; commandQueue.RemoveAt(0); } if (commandQueue.Count == 0) { commandEvent.Reset( ); } } if ((commandToProcess != null) && (commandToProcess.Type != HttpRequestType.Unknown)) { HandleHttpCommand(commandToProcess); } } }
// Add the HTTP request to the internal queue and signal background thread to handle it private uint EnqueueRequest(HttpCommand command, bool clearPreviousRequests) { lock ( sync ) { command.Id = ++commandCounter; if (commandCounter == uint.MaxValue) { commandCounter = 0; } if (clearPreviousRequests) { ClearRequests(command.Url); } commandQueue.Add(command); if (commandEvent != null) { commandEvent.Set( ); } } return(command.Id); }
// Handle the specified HTTP command private void HandleHttpCommand(HttpCommand commandToProcess) { HttpWebRequest request = null; WebResponse response = null; Stream stream = null; byte[] buffer = new byte[bufferSize]; int read, totalRead = 0; try { request = (HttpWebRequest)WebRequest.Create(baseAddress + commandToProcess.Url); request.Timeout = requestTimeout; if ((!string.IsNullOrEmpty(login)) && (password != null)) { request.Credentials = new NetworkCredential(login, password); } // send POST data if (commandToProcess.Type == HttpRequestType.Post) { byte[] data = Encoding.ASCII.GetBytes(commandToProcess.Body); request.Method = "POST"; request.ContentType = "text/plain"; request.ContentLength = data.Length; stream = request.GetRequestStream( ); stream.Write(data, 0, data.Length); stream.Close( ); stream.Dispose( ); stream = null; } // get response and its stream response = request.GetResponse( ); stream = response.GetResponseStream( ); stream.ReadTimeout = requestTimeout; // read response while (!stopEvent.WaitOne(0, false)) { int toRead = Math.Min(readSize, bufferSize - totalRead); if (toRead == 0) { throw new ApplicationException("Read buffer is too small"); } // read next portion from stream if ((read = stream.Read(buffer, totalRead, toRead)) == 0) { break; } toRead += read; } string responseString = System.Text.Encoding.UTF8.GetString(buffer); if (HttpCommandCompletion != null) { HttpCommandCompletion(this, new HttpCommandEventArgs(commandToProcess.Id, true, responseString)); } } catch (Exception exception) { if (HttpCommandCompletion != null) { HttpCommandCompletion(this, new HttpCommandEventArgs(commandToProcess.Id, false, exception.Message)); } } finally { if (request != null) { request.Abort( ); request = null; } if (stream != null) { stream.Close( ); stream.Dispose( ); stream = null; } if (response != null) { response.Close( ); response = null; } } }