Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6557325
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T13:03:35+00:00 2026-05-25T13:03:35+00:00

I asked this question before but I’m going to complete the question with a

  • 0

I asked this question before but I’m going to complete the question with a solution proposed and make another question.

I’m using this class to make an async WebRequest:

class HttpSocket
{
    public static void MakeRequest(Uri uri, Action<RequestCallbackState> responseCallback)
    {
        WebRequest request = WebRequest.Create(uri);
        request.Proxy = null;

        Task<WebResponse> asyncTask = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
        ThreadPool.RegisterWaitForSingleObject((asyncTask as IAsyncResult).AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), request, 1000, true);
        asyncTask.ContinueWith(task =>
            {
                WebResponse response = task.Result;
                Stream responseStream = response.GetResponseStream();
                responseCallback(new RequestCallbackState(response.GetResponseStream()));
                responseStream.Close();
                response.Close();
            });
    }

    private static void TimeoutCallback(object state, bool timedOut)
    {
        Console.WriteLine("Timeout: " + timedOut);
        if (timedOut)
        {
            Console.WriteLine("Timeout");
            WebRequest request = (WebRequest)state;
            if (state != null)
            {
                request.Abort();
            }
        }
    }
}

And i’m testing the class with this code:

class Program
{
    static void Main(string[] args)
    {
        // Making a request to a nonexistent domain.
        HttpSocket.MakeRequest(new Uri("http://www.google.comhklhlñ"), callbackState =>
            {
                if (callbackState.Exception != null)
                    throw callbackState.Exception;
                Console.WriteLine(GetResponseText(callbackState.ResponseStream));
            });
        Thread.Sleep(100000);
    }

    public static string GetResponseText(Stream responseStream)
    {
        using (var reader = new StreamReader(responseStream))
        {
            return reader.ReadToEnd();
        }
    }
}

Once executed, the callback is reached immediately, showing “Timeout: false” and there aren’t more throws, so the timeout isn’t working.

This is a solution proposed in the original thread but, as you could see, the code works for him.

What I’m doing wrong?

EDIT: Other classes used by the code:

class RequestCallbackState
{
    public Stream ResponseStream { get; private set; }
    public Exception Exception { get; private set; }

    public RequestCallbackState(Stream responseStream)
    {
        ResponseStream = responseStream;
    }

    public RequestCallbackState(Exception exception)
    {
        Exception = exception;
    }
}

class RequestState
{
    public byte[] RequestBytes { get; set; }
    public WebRequest Request { get; set; }
    public Action<RequestCallbackState> ResponseCallback { get; set; }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T13:03:36+00:00Added an answer on May 25, 2026 at 1:03 pm

    This approach works. I would recommend switching this to explicitly handle exceptions (including your timeout, but also bad domain names, etc) slightly differently. In this case, I’ve split this into a separate continuation.

    In addition, in order to make this very explicit, I’ve shorted the timeout time, put a “real” but slow domain in, as well as added an explicit timeout state you can see:

    using System;
    using System.IO;
    using System.Net;
    using System.Threading;
    using System.Threading.Tasks;
    
    class HttpSocket
    {
        private const int TimeoutLength = 100;
    
        public static void MakeRequest(Uri uri, Action<RequestCallbackState> responseCallback)
        {
            WebRequest request = WebRequest.Create(uri);
            request.Proxy = null;
    
            Task<WebResponse> asyncTask = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
            ThreadPool.RegisterWaitForSingleObject((asyncTask as IAsyncResult).AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), request, TimeoutLength, true);
            asyncTask.ContinueWith(task =>
                {
                    WebResponse response = task.Result;
                    Stream responseStream = response.GetResponseStream();
                    responseCallback(new RequestCallbackState(response.GetResponseStream()));
                    responseStream.Close();
                    response.Close();
                }, TaskContinuationOptions.NotOnFaulted);
            // Handle errors
            asyncTask.ContinueWith(task =>
                {
                    var exception = task.Exception;
                    var webException = exception.InnerException;
    
                    // Track whether you cancelled or not... up to you...
                    responseCallback(new RequestCallbackState(exception.InnerException, webException.Message.Contains("The request was canceled.")));
                }, TaskContinuationOptions.OnlyOnFaulted);
        }
    
        private static void TimeoutCallback(object state, bool timedOut)
        {
            Console.WriteLine("Timeout: " + timedOut);
            if (timedOut)
            {
                Console.WriteLine("Timeout");
                WebRequest request = (WebRequest)state;
                if (state != null)
                {
                    request.Abort();
                }
            }
        }
    }
    
    class RequestCallbackState
    {
        public Stream ResponseStream { get; private set; }
        public Exception Exception { get; private set; }
    
        public bool RequestTimedOut { get; private set; }
    
        public RequestCallbackState(Stream responseStream)
        {
            ResponseStream = responseStream;
        }
    
        public RequestCallbackState(Exception exception, bool timedOut = false)
        {
            Exception = exception;
            RequestTimedOut = timedOut;
        }
    }
    
    class RequestState
    {
        public byte[] RequestBytes { get; set; }
        public WebRequest Request { get; set; }
        public Action<RequestCallbackState> ResponseCallback { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            // Making a request to a nonexistent domain.
            HttpSocket.MakeRequest(new Uri("http://www.tanzaniatouristboard.com/"), callbackState =>
                {
                    if (callbackState.RequestTimedOut)
                    {
                        Console.WriteLine("Timed out!");
                    }
                    else if (callbackState.Exception != null)
                        throw callbackState.Exception;
                    else
                        Console.WriteLine(GetResponseText(callbackState.ResponseStream));
                });
            Thread.Sleep(100000);
        }
    
        public static string GetResponseText(Stream responseStream)
        {
            using (var reader = new StreamReader(responseStream))
            {
                return reader.ReadToEnd();
            }
        }
    }
    

    This will run, and show a timeout appropriately.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I asked this question before but didn't make it clear that I meant in
This question was asked before but the solution is not applicable in my case.
I have asked this before but I didn't get the question right so the
This question has been asked before ( link ) but I have slightly different
I know this question has been asked before, but I ran into a problem.
This question may have been asked before, but I had trouble finding an answer,
Maybe this question has been asked many times before, but I never found a
I know this question has been asked a bit before. But looking around I
No doubt elements of this question have been asked before, but I'm having trouble
This has been asked before (question no. 308581) , but that particular question and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.