I'm attempting to mimic the same output for two different implementations asynchronous functionality - the only difference in my mind being return mechanisms. I've boiled down the two examples to the most abstract example I can make them.
For example, the first implementation is very simplistic and behaves as I would expect:
Main()
{
DoStuff();
Console.WriteLine("Hello");
}
async void DoStuff()
{
try
{
string output = await Task.Run(() =>
{
return longRunningMethod();
});
Console.WriteLine(output);
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
string longRunningMethod()
{
Console.WriteLine("Sleeping...");
Thread.Sleep(2000);
Console.WriteLine("... woken up!");
return "World!";
}
/*--------- OUTPUT----------
* Hello
* Sleeping...
*...woken up!
* World!
I then thought to myself that it would be more useful if you could use the result of the async method in a method call rather than return void and embed the behaviour into the void
method itself.
Using some reference material and muddling along I have something in my mind that I thought would work but, as below, is returning in the incorrect order.
Main()
{
Console.WriteLine(DoStuff().Result);
Console.WriteLine("Hello");
}
async Task<string> DoStuff()
{
try
{
return await Task.Run(() =>
{
return longRunningMethod();
});
}
catch(Exception ex)
{
return ex.ToString();
}
}
string longRunningMethod()
{
Console.WriteLine("Sleeping...");
Thread.Sleep(2000);
Console.WriteLine("... woken up!");
return "World!";
}
/*--------- OUTPUT----------
* Sleeping...
*...woken up!
* World!
* Hello
In my mind the two snippets should basically be synonymous though this is clearly not the case. An error on my part is causing the code to run synchronously.
Either I'm being dumb or I'm fundamentally misunderstanding something.
PS. If anyone has any advice titling a question like this, feel free to edit/comment as I'm aware it's not particularly informative.