As Richard said, you can't do anything in your code to make the remote site return a response any faster.
However, you can potentially shave a small amount of time and memory off by streaming the response, and only reading up to the closing
</head>
tag.
For example:
public static class HttpContentExtensions
{
public static async Task<string> ExtractHtmlHeadAsync(this HttpContent content)
{
if (content is null) throw new ArgumentNullException(nameof(content));
using (var stream = await content.ReadAsStreamAsync())
using (var reader = new StreamReader(stream))
{
int charsRead;
char[] buffer = new char[1024];
var sb = new StringBuilder();
while ((charsRead = await reader.ReadBlockAsync(buffer, 0, buffer.Length)) != 0)
{
sb.Append(buffer, 0, charsRead);
int index = FindClosingHeadIndex(sb);
if (index != -1)
{
sb.Length = index + 7;
break;
}
}
return sb.ToString();
}
}
private static int FindClosingHeadIndex(StringBuilder sb)
{
for (int index = 0; index < sb.Length - 6; index++)
{
if (sb[index] == '<'
&& sb[index + 1] == '/'
&& sb[index + 6] == '>'
&& (sb[index + 2] == 'h' || sb[index + 2] == 'H')
&& (sb[index + 3] == 'e' || sb[index + 3] == 'E')
&& (sb[index + 4] == 'a' || sb[index + 4] == 'A')
&& (sb[index + 5] == 'd' || sb[index + 2] == 'D'))
{
return index;
}
}
return -1;
}
}
private void Button_Clicked(object sender, EventArgs e)
{
if (!Uri.TryCreate(EntryURL.Text, UriKind.Absolute, out var url))
{
MessageBox.Show("Please enter a valid URL!");
return;
}
_ = LoadWebsiteTitleAsync(url);
}
private async Task LoadWebsiteTitleAsync(Uri url)
{
LabelWebsiteURL.Text = url.ToString();
var hc = new HttpClient();
using (var response = await hc.GetAsync(url, HttpCompletionOption.ResponseContentRead))
{
string source = await response.Content.ExtractHtmlHeadAsync();
Match match = Regex.Match(source, @"\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\s*\</title\>", RegexOptions.IgnoreCase);
string title = match.Success ? match.Groups["Title"].Value : "# Untitled page #";
LabelWebsiteTitle.Text = title;
}
}
NB: Avoid async void methods | You’ve Been Haacked[
^]
Async Guidance - David Fowler[
^]