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" %>

    <form runat="server">

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

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));
            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"))
                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



Add a RELEVANT link (not required)

Upload an image (not required)

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

Admin Ren's Biking Blog