Search code examples
c#httpwebrequestmultithreadingiasyncresult

Help threading HttpWebRquest in c#


Hi guys just wondering if somebody could help me try and correctly thread my application, I am constantly hitting an hurdle after another, I have never been to clued up on threading in applications. I have tryed following this http://www.developerfusion.com/code/4654/asynchronous-httpwebrequest/ tutorial.

basically I'm just trying to stop my request from hanging my application

public class Twitter
{
    private const string _username = "****",
        _password = "****";

    private WebResponse webResp;

    public string getTimeLine()
    {
        Thread thread = new Thread(new ThreadStart(TwitterRequestTimeLine));
        thread.IsBackground = true;
        thread.Start();

        using (Stream responseStream = webResp.GetResponseStream())
        {
            //
            using (StreamReader reader = new StreamReader(responseStream))
            {
                return reader.ReadToEnd();
            }
        }
    }

    private void TwitterRequestTimeLine()
    {
        string aUrl = "http://168.143.162.116/statuses/home_timeline.xml";
        HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(aUrl);
        SetRequestParams(request);  
        request.Credentials = new NetworkCredential(_username, _password);
        //WebResponse tempResp = request.GetResponse();
        ThreadState state = new ThreadState();
        IAsyncResult result = request.BeginGetResponse(new AsyncCallback(???), ???);

    }



      private static void SetRequestParams( HttpWebRequest request )
  {
      request.Timeout = 500000;
      request.Method = "POST";
      request.ContentType = "application/x-www-form-urlencoded";
      request.UserAgent = "AdverTwitment";
  }
}
}

anyone help would be greatly appricated


Solution

  • If this is a WinForms app, the easiest way to keep the GUI responsive while executing the WebRequest is to use a BackgroundWorker component. Drop a BackgroundWorker on your form and call its RunWorkAsync() method. Put the code to execute the WebRequest and read the Response in the DoWork event handler.