开发者

Using a timeout callback in async requests

开发者 https://www.devze.com 2023-04-04 04:07 出处:网络
I asked this question before but I\'m going to complete the question with a solution proposed and make another question.

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> ResponseC开发者_开发技巧allback { get; set; }
}


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.


Use 2 different classes:

class RequestCallbackException : Exception
{
    public RequestCallbackException(Stream responseStream, Exception exception) : base(exception)
    {
    }
}

and

class RequestCallbackStream
{
    public Stream ResponseStream { get; private set; }

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

You will notice that sometimes GetResponseStream() returns null, which immediately raise an exception in

asyncTask.ContinueWith() -->

GetResponseText(callbackState.ResponseStream)-->

using (var reader = new StreamReader(responseStream)) // responseStream is null
{
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号