Reputation: 622
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 :
Task.Run
in 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.
Upvotes: 0
Views: 869
Reputation: 457302
async
/await
has nothing to do with Task.Run
; however, they do work well together in some scenarios.
Task.Run
runs some code on a thread pool thread. async
/await
is a code transformation that allows you to write asynchronous code in a more natural, imperative manner (see my async
intro for more details about how async
works).
Is it mandatory to use Task.Run in any async and await method because I just removed and the program becomes synchronous.
Not at all! async
/await
are very commonly used without Task.Run
. Anytime that you have a truly asynchronous operation, then you can use async
/await
. Generally speaking, anything I/O-based is a good example of a naturally asynchronous operation. So, you can use something like HttpClient.GetStringAsync
using just async
/await
without any Task.Run
at all.
Note, however, that it is almost always wrong to use async
without await
. The compiler will give you a warning for LongRunningOperation
, informing you of the fact that it's not actually asynchronous.
How many number of threads while the following of code creates? Task.Run(() => {demo.DoStuff()};
That code just queues DoStuff
to the thread pool. A thread pool thread will execute DoStuff
. Thread creation is dependent on a lot of other factors.
Upvotes: 3