Can't specify the 'async' modifier on the 'Main' method of a console app

后端 未结 16 2036
后悔当初
后悔当初 2020-11-21 07:44

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

16条回答
  •  遇见更好的自我
    2020-11-21 08:25

    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 or Result, and there's nothing wrong with that. But be aware that there are two important differences: 1) all async continuations run on the thread pool rather than the main thread, and 2) any exceptions are wrapped in an AggregateException.

    (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;
            });
    

提交回复
热议问题