Sam Grondahl
Sam Grondahl

Reputation: 2467

WebRequest/WebResponse blocking in C#

I am trying to fire off a signal locally from C#. The goal is to make a request to localhost/serv?stream=SOME_STREAM. I don't care about getting the response from the server, all I need is for the server to receive the request. Right now I am using the following code, though I don't really care about using these objects -- any solution is fine:

    private void updateStreams(string streamname)
    {
        WebRequest myWebRequest = WebRequest.Create(new Uri("http://localhost/serv?stream=" + streamname));
        WebResponse myWebResponse = myWebRequest.GetResponse();
        myWebResponse.Close();
    }

I've tried some debugging, and the blocking call seems to be myWebRequest.GetResponse(), but this line is critical because the request doesn't get made without it. I've also tried the following code, which blocks at the same point:

        var myWebRequest = (System.Net.HttpWebRequest)WebRequest.Create(new Uri("http://localhost/serv?stream=" + sesh.session_name));
        using (var myWebResponse = (System.Net.HttpWebResponse)myWebRequest.GetResponse())
        {
            var responseStream = myWebResponse.GetResponseStream();
            responseStream.ReadTimeout = 2; 
            responseStream.Close();
            responseStream.Dispose();
            myWebResponse.Close();
        }

Upvotes: 1

Views: 3187

Answers (2)

akton
akton

Reputation: 14386

If you just do not want the code to block and are using .Net 4.5, try WebRequest.GetResponseAsync(), or WebRequest.BeginGetResponse() in earlier versions of the framework.

Upvotes: 1

Icarus
Icarus

Reputation: 63966

You can use WebClient.DownloadStringAsync() as so:

WebClient wc = new WebClient();
wc.DownloadStringCompleted += new  DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.DownloadStringAsync(new Uri("http://localhost/serv?stream=" + streamname));

This will fire off the request and call the wc_DownloadStringCompleted method when the request is finished without blocking the main Thread.

Upvotes: 1

Related Questions