Reputation: 21
I have many win services and console applications that run on task scheduler, as netstandard 2.0 and core .net turn all I/O calls to async all my code is written as async/await model, Is there any advantage of using this pattern when I will not have any UI that can be frozen?
Upvotes: 3
Views: 140
Reputation: 457127
Is there any advantage of using this pattern when I will not have any UI that can be frozen?
The point of async
/await
is to free up threads. Preventing frozen UIs is one specific example of this: async
/await
can be used to free up the UI thread, so it is not frozen.
There are other scenarios where freeing up threads is helpful. E.g., for web servers, freeing up threads allows more scalability.
There are some scenarios where freeing up threads isn't as helpful. For desktop apps, having an extra thread (or ten) isn't as big of a deal, because most desktop computers are massively underutilized. For console apps in particular, you want to block the main thread because otherwise the app would exit early. However, this is not to say that async
shouldn't be used in console apps; I sometimes use it just because you can do asynchronous concurrency as easily as parallel concurrency, particularly if the APIs you're calling are asynchronous.
So, while there are situations where async
is a clear win, there are other situations where it's more of a judgement call. And even if you do determine that asynchronous code would be more maintainable for your Win32 service, would it be worth the switch? That's the question you'd have to answer yourself.
Upvotes: 1
Reputation: 9606
Yes, there is an advantage.
Imagine there is an I/O operation in your service that takes 3 seconds to get data from some socket. Using Async/Await pattern allows you to do other CPU bound work in those 3 seconds without blocking the thread.
some basic example
var obj = new Demo();
var task1 = obj.WaitForIO(); //Imagine this as a database call that takes 5 seconds to finish
var task2 = obj.DoSomethingElse(); //Imagine this as some CPU bound work eg: some calculations
await Task.WhenAll(task1,task2);
public class Demo
{
public async Task WaitForIO()
{
await Task.Delay(5000);
Console.WriteLine("IO Done");
}
public async Task DoSomethingElse()
{
for(var i=1;i<10;i++)
{
Console.WriteLine(i);
await Task.Delay(1000);
}
}
}
Output:
1
2
3
4
5
IO Done
6
7
8
9
Upvotes: 2