I'm just learning about task, and async/await implementation and I'm struggling with a simple code example so I was hoping someone could share some lights as to what is going on.
here's the code:
public async Task<string> DoStuff()
{
Console.WriteLine("Long running op started");
var myString = await Task<string>.Run(() =>
{
var result = "Test";
for (int counter = 0; counter < 5000; counter++)
{
Console.WriteLine(counter);
}
return (result);
});
Console.WriteLine(myString);
return myString;
}
private void button1_Click(object sender, EventArgs e)
{
DoStuff();
while (true) {
Console.WriteLine("Doing Stuff on the Main Thread...................");
System.Threading.Thread.Sleep(100);
}
So the result of the execution is like this: Long running op started 0 1 2 .... 225 226 Doing Stuff on the Main Thread................... 227 .... etc...
However the code in the DoStuff method that is located after the Task.Run is never reached. And I don't understand why. Of course if I put an await in front of the DoStuff call it works but then the main thread is stuck waiting for execution. This is all for learning purpose only. Thanks
EDIT: as the comments below are saying, it is effectively working when the code is a Main entry program and it was originally in a button click event, this is where the problem occurs actually sorry about the confusion.