namespace WebReader
{
public partial class frm_Main : Form
{
public frm_Main()
{
InitializeComponent();
}
private void frm_Main_Load(object sender, EventArgs e)
{
using var clt= new HttpClient();
var res = clt.GetAsync("https://daera.net/dmoon/testfile.txt");
while (true)
{
if (res.IsCompletedSuccessfully)
{
var msg = clt.GetStringAsync("https://daera.net/dmoon/testfile.txt");
MessageBox.Show(msg.ToString());
break;
}
}
}
}
}
This code is supposed to show the contents of the text file https://daera.net/dmoon/testfile.txt
, but it shows a message box with some technical information regarding clt object and nothing else.
What am I doing wrong? I am using Visual Studio 2019.
2
Answers
Oversimplifying, but you want to
await
the results of Async methods:Do this, and you won’t need the
while (true)
loop.As I said in the comments, the
GetStringAsync()
call is also asynchronous and returns aTask<String>
.You have several options for synchronizing these tasks with your main program.
while(true)
loop checking forIsCompletedSuccessfully
. This is not recommended at all, because it eats your resources doing nothing.Task.Wait()
. This is a blocking call and what you’re looking for. (Edited: it’s closer to your original loop without eating resources; but you probably don’t want to block your form until the HTTP call ends, which would make your program unresponsive. Look for option 3 orTask.ContinueWith()
)await
as in @Joel’s answer (*).This is your code, using option 1 for
GetAsync()
(again, not recommended) and option 2 forGetStringAsync()
.(*) When you use
await
before an asynchronous function call, the current function (ie. the caller) won’t execute the instructions following the call until the asynchronous task completes; but it will immediately return to its own caller. That is, the caller will also be asynchronous (and that’s the reason for the mandatoryasync
keyword).