I am new to asynchronous programming with the async
modifier. I am trying to figure out how to make sure that my Main
method of a console application actually runs asynchronously.
class Program
{
static void Main(string[] args)
{
Bootstrapper bs = new Bootstrapper();
var list = bs.GetList();
}
}
public class Bootstrapper {
public async Task<List<TvChannel>> GetList()
{
GetPrograms pro = new GetPrograms();
return await pro.DownloadTvChannels();
}
}
I know this is not running asynchronously from "the top." Since it is not possible to specify the async
modifier on the Main
method, how can I run code within main
asynchronously?
I'll add an important feature that all of the other answers have overlooked: cancellation.
One of the big things in TPL is cancellation support, and console apps have a method of cancellation built in (CTRL+C). It's very simple to bind them together. This is how I structure all of my async console apps:
To avoid freezing when you call a function somewhere down the call stack that tries to re-join the current thread (which is stuck in a Wait), you need to do the following:
(the cast is only required to resolve ambiguity)
On MSDN, the documentation for Task.Run Method (Action) provides this example which shows how to run a method asynchronously from
main
:Note this statement that follows the example:
So, if instead you want the task to run on the main application thread, see the answer by @StephenCleary.
And regarding the thread on which the task runs, also note Stephen's comment on his answer:
(See Exception Handling (Task Parallel Library) for how to incorporate exception handling to deal with an
AggregateException
.)Finally, on MSDN from the documentation for Task.Delay Method (TimeSpan), this example shows how to run an asynchronous task that returns a value:
Note that instead of passing a
delegate
toTask.Run
, you can instead pass a lambda function like this: