Reputation: 129
Can anybody provide any examples/code snippet to use below method.
public static Task Run(Func<Task> function);
I am trying to understand how to use the above overloaded method but I did not find any code in web.
As far as I understand this method takes func delegate
as input parameter which should return a Task so please provide me some code snippet.
Thanks, Vinod
Upvotes: 2
Views: 520
Reputation: 37770
This overload is often used to offload task to a thread pool thread.
Suppose you wrote this method inside console app:
private static async Task DoSomeHeavyInitializationAsync()
{
// some heavy calculations;
// some async I/O (e.q. reading from database, file, etc);
await SomeMethodAsync(...);
// again some heavy calculations, async I/O, etc...
}
Now you want to call it from Program.Main
, and keep Main
responsive: if user don't want to wait app being initialized, he can press [enter] and terminate the app.
So, you need to offload task to be sure, that its code won't run on main thread. Task Run(Func<Task>)
helps you:
static void Main(string[] args)
{
Task.Run(DoSomeHeavyInitializationAsync);
// do something else...
Console.ReadLine();
}
Upvotes: 3