Home

C# HttpClient and Async Super Basic Example

Blog Date 28 September 2023

Still not gotten a full grasp of Async as yet. BUT. NOTE!! The page directive needs "Async="true""

The Page

<%@ Page Title="" Async="true" Language="C#" AutoEventWireup="true" CodeBehind="Async.aspx.cs" Inherits="abcd.Async" %>

<html>
<head>
    <title>Async
    </title>
</head>
<body>
    <form runat="server">
        <h1>Async</h1>

        <asp:TextBox ID="MyShow" TextMode="MultiLine" Width="500px" Height="500px" runat="server" />
    </form>
</body>
</html>

The Code Behind

using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.UI;

namespace abcd
{
    public partial class Async : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterAsyncTask(new PageAsyncTask(MyTask));
            MyTask();
            MyShow.Text = "OK"; //This will NOT be shown as... the "MyTask()" above
                                //will run in it's own sweet time and OVERWRITE the OK
        }

        HttpClient client = new HttpClient();   //ALWAYS put this outside the method. Why?
                                                //Not sure but everyone says if it's inside it creates
                                                //multiple instances of the client and eats resources
                                                //I think this "shares" the client.

        async Task MyTask()
        {
            using (HttpResponseMessage response = await client.GetAsync("https://bbc.co.uk"))
            {
                response.EnsureSuccessStatusCode();
                MyShow.Text = await response.Content.ReadAsStringAsync();
                        //try adding "+=" rather than "=" above. As this is run in it's own
                        //time you'll now see the "OK" that was added in Page_Load
                        //then the BBC's HTML
            }
        }
    }
}

Reader's Comments

Post Your Comment Posts/Links Rules

Name

Comment

Add a RELEVANT link (not required)

Upload an image (not required)

No uploaded image
Real person number
Please enter the above number below




Home
Admin Ren's Biking Blog