Question

My desktop .NET 3.5 application uses WebRequest.BeginGetResponse to issue a request which is used to implement long polling. This request typically takes 10 seconds or more to process. The trouble is BeginGetResponse performs the waiting for the request to complete on the thread pool, which then seems to be starving. Is there some way how to specify a custom thread or a custom thread for BeginGetResponse to use?

As an alternative I could also use my own thread performing synchronous request using WebRequest.GetResponse (hopefully this is really synchronous in .NET 3.5, it was not in .NET 1.0), but then I have a problem I am unable to terminate the request prematurely when I need to quit the application, as I see no clean way how to abort a synchronous request.

Was it helpful?

Solution

I don't know if you're using WPF or Windows forms.. Here's a WPF Example.

        WebRequest w = HttpWebRequest.Create("http://www.google.com");

        Dispatcher dispatcher = Dispatcher.CurrentDispatcher;

        Thread thread = new Thread(new ThreadStart(() =>
            {
                WebResponse response = w.GetResponse();
                dispatcher.BeginInvoke(new Action(() =>
                {

                    // Handle response on the dispatcher thread.

                }), null);
            }));

        thread.IsBackground = true;
        thread.Start();

Notice the IsBackground = true. So your application will terminate it on exit. It's also possible to put HttpWebRequest.Create inside the thread method.

Windows.Form equivalent

        WebRequest w = HttpWebRequest.Create("http://www.google.com");

        Thread thread = new Thread(new ThreadStart(() =>
            {
                WebResponse response = w.GetResponse();
                this.BeginInvoke(new Action(() =>
                {

                    // Handle response on the dispatcher thread.

                }), null);
            }));

        thread.IsBackground = true;
        thread.Start();

Where this is a Form/Control

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top