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 applicati
On MSDN, the documentation for Task.Run Method (Action) provides this example which shows how to run a method asynchronously from main
:
using System;
using System.Threading;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
ShowThreadInfo("Application");
var t = Task.Run(() => ShowThreadInfo("Task") );
t.Wait();
}
static void ShowThreadInfo(String s)
{
Console.WriteLine("{0} Thread ID: {1}",
s, Thread.CurrentThread.ManagedThreadId);
}
}
// The example displays the following output:
// Application thread ID: 1
// Task thread ID: 3
Note this statement that follows the example:
The examples show that the asynchronous task executes on a different thread than the main application thread.
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:
You can use a simple
Wait
orResult
, and there's nothing wrong with that. But be aware that there are two important differences: 1) allasync
continuations run on the thread pool rather than the main thread, and 2) any exceptions are wrapped in anAggregateException
.
(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:
using System;
using System.Threading.Tasks;
public class Example
{
public static void Main()
{
var t = Task.Run(async delegate
{
await Task.Delay(TimeSpan.FromSeconds(1.5));
return 42;
});
t.Wait();
Console.WriteLine("Task t Status: {0}, Result: {1}",
t.Status, t.Result);
}
}
// The example displays the following output:
// Task t Status: RanToCompletion, Result: 42
Note that instead of passing a delegate
to Task.Run
, you can instead pass a lambda function like this:
var t = Task.Run(async () =>
{
await Task.Delay(TimeSpan.FromSeconds(1.5));
return 42;
});