I have got a simple program for async and await:
class Program { static void Main() { var demo = new AsyncAwaitDemo(); Task.Run(() => {demo.DoStuff()}; while (true) { Console.WriteLine("Doing Stuff on the Main Thread..................."); } } } public class AsyncAwaitDemo { public async Task DoStuff() { await LongRunningOperation(); } private static async Task<string> LongRunningOperation() { int counter; for (counter = 0; counter < 50000; counter++) { Console.WriteLine(counter); } return "Counter = " + counter; } } My first question is :
- Is it mandatory to use
Task.Runin any async and await method because I just removed and the program becomes synchronous.I am aware of the fact that await is used to create suspension points and doesnt get executed further until the awaited function completes for that thread.
Secondly,
How many number of threads while the following of code creates?
Task.Run(() => {demo.DoStuff()};
If it is more than one , then is the number of threads dependent on the inner operation , in this example it is for loop with counter .
I am beginning to understand the asynchronous programming in C# , read and practiced few samples . I am able to get the context almost apart from the clarifications I asked as above.