HttpWebRequest.EndGetResponse(IAsyncResult) Yöntem

Tanım

İnternet kaynağına yönelik zaman uyumsuz bir isteği sonlandırır.

C#
public override System.Net.WebResponse EndGetResponse(IAsyncResult asyncResult);

Parametreler

asyncResult
IAsyncResult

Yanıt için bekleyen istek.

Döndürülenler

İnternet kaynağından gelen yanıtı içeren bir WebResponse.

Özel durumlar

asyncResult null.

Bu yöntem daha önce asyncResultkullanılarak çağrıldı.

-veya-

ContentLength özelliği 0'dan büyük ancak veriler istek akışına yazılmamıştır.

Abort() daha önce çağrıldı.

-veya-

İstek işlenirken bir hata oluştu.

asyncResult BeginGetResponse(AsyncCallback, Object)çağrısından geçerli örnek tarafından döndürülmedi.

Örnekler

Aşağıdaki kod örneği, bir İnternet kaynağı için zaman uyumsuz isteği sonlandırmak için EndGetResponse yöntemini kullanır.

C#
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;

public static class WebRequestAPMSample
{
    private const int BufferSize = 1024;

    private class RequestState
    {
        public StringBuilder ResponseBuilder { get; }
        public byte[] ReadBuffer { get; }
        public WebRequest Request { get; }
        public WebResponse Response { get; set; }
        public Stream ResponseStream { get; set; }
        public RequestState(WebRequest request)
        {
            ReadBuffer = new byte[BufferSize];
            ResponseBuilder = new StringBuilder();
            Request = request;
        }
        public void OnResponseBytesRead(int read) => ResponseBuilder.Append(Encoding.UTF8.GetString(ReadBuffer, 0, read));
    }

    public static ManualResetEvent allDone = new ManualResetEvent(false);
    

    public static void Main()
    {
        try
        {
            // Create a WebRequest object to the desired URL.
            WebRequest webRequest = WebRequest.Create("http://www.contoso.com");
            webRequest.Timeout = 10_000; // Set 10sec timeout.

            // Create an instance of the RequestState and assign the previous myHttpWebRequest
            // object to its request field.
            RequestState requestState = new RequestState(webRequest);

            // Start the asynchronous request.
            IAsyncResult result = webRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), requestState);

            // Wait for the response or for failure. The processing happens in the callback.
            allDone.WaitOne();

            // Release the WebResponse resources.
            requestState.Response?.Close();
        }
        catch (WebException e)
        {
            Console.WriteLine("\nMain(): WebException raised!");
            Console.WriteLine("\nMessage:{0}", e.Message);
            Console.WriteLine("\nStatus:{0}", e.Status);
            Console.WriteLine("Press any key to continue..........");
            Console.Read();
        }
        catch (Exception e)
        {
            Console.WriteLine("\nMain(): Exception raised!");
            Console.WriteLine("Source :{0} ", e.Source);
            Console.WriteLine("Message :{0} ", e.Message);
            Console.WriteLine("Press any key to continue..........");
            Console.Read();
        }
    }

    private static void HandleSyncResponseReadCompletion(IAsyncResult asyncResult)
    {
        RequestState requestState = (RequestState)asyncResult.AsyncState;
        Stream responseStream = requestState.ResponseStream;

        bool readComplete = false;
        while (asyncResult.CompletedSynchronously && !readComplete)
        {
            int read = responseStream.EndRead(asyncResult);
            if (read > 0)
            {
                requestState.OnResponseBytesRead(read);
                asyncResult = responseStream.BeginRead(requestState.ReadBuffer, 0, BufferSize, new AsyncCallback(ReadCallBack), requestState);
            }
            else
            {
                readComplete = true;
                HandleReadCompletion(requestState);
            }
        }
    }

    private static void ResponseCallback(IAsyncResult asynchronousResult)
    {
        try
        {
            // AsyncState is an instance of RequestState.
            RequestState requestState = (RequestState)asynchronousResult.AsyncState;
            WebRequest request = requestState.Request;
            requestState.Response = request.EndGetResponse(asynchronousResult);

            // Read the response into a Stream.
            Stream responseStream = requestState.Response.GetResponseStream();
            requestState.ResponseStream = responseStream;

            // Begin the Reading of the contents of the HTML page and print it to the console.
            IAsyncResult asynchronousReadResult = responseStream.BeginRead(requestState.ReadBuffer, 0, BufferSize, new AsyncCallback(ReadCallBack), requestState);
            HandleSyncResponseReadCompletion(asynchronousReadResult);
        }
        catch (WebException e)
        {
            Console.WriteLine("\nRespCallback(): Exception raised!");
            Console.WriteLine("\nMessage:{0}", e.Message);
            Console.WriteLine("\nStatus:{0}", e.Status);
            allDone.Set();
        }   
    }

    // Print the webpage to the standard output, close the stream and signal completion.
    private static void HandleReadCompletion(RequestState requestState)
    {
        Console.WriteLine("\nThe contents of the Html page are : ");
        if (requestState.ResponseBuilder.Length > 1)
        {
            string stringContent;
            stringContent = requestState.ResponseBuilder.ToString();
            Console.WriteLine(stringContent);
        }
        Console.WriteLine("Press any key to continue..........");
        Console.ReadLine();

        requestState.ResponseStream.Close();
        allDone.Set();
    }

    private static void ReadCallBack(IAsyncResult asyncResult)
    {
        if (asyncResult.CompletedSynchronously)
        {
            // To avoid recursive synchronous calls into ReadCallBack,
            // synchronous completion is handled at the BeginRead call-site.
            return;
        }

        try
        {
            RequestState requestState = (RequestState)asyncResult.AsyncState;
            Stream responseStream = requestState.ResponseStream;
            int read = responseStream.EndRead(asyncResult);
            // Read the HTML page and then print it to the console.
            if (read > 0)
            {
                requestState.OnResponseBytesRead(read);
                IAsyncResult asynchronousResult = responseStream.BeginRead(requestState.ReadBuffer, 0, BufferSize, new AsyncCallback(ReadCallBack), requestState);
                HandleSyncResponseReadCompletion(asynchronousResult);
            }
            else
            {
                HandleReadCompletion(requestState);
            }
        }
        catch (WebException e)
        {
            Console.WriteLine("\nReadCallBack(): Exception raised!");
            Console.WriteLine("\nMessage:{0}", e.Message);
            Console.WriteLine("\nStatus:{0}", e.Status);
            allDone.Set();
        }
    }
}

Açıklamalar

Dikkat

WebRequest, HttpWebRequest, ServicePointve WebClient kullanım dışıdır ve bunları yeni geliştirme için kullanmamalısınız. Bunun yerine HttpClient kullanın.

EndGetResponse yöntemi, BeginGetResponse yöntemi çağrılarak başlatılan bir İnternet kaynağı için zaman uyumsuz isteği tamamlar.

Dikkat

Akışı kapatmak ve bağlantıyı serbest bırakmak için Close yöntemini çağırmanız gerekir. Bunun yapılmaması uygulamanızın bağlantılarının dolmasına neden olabilir.

Not

Bu üye, uygulamanızda ağ izlemeyi etkinleştirdiğinizde izleme bilgilerini döndürür. Daha fazla bilgi için bkz. .NET FrameworkAğ İzleme.

Şunlara uygulanır

Ürün Sürümler
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0