使用C代码启动任务

问题描述:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace TaskStart 
{ 
    class Program 
    { 
     private static void PrintMessage() 
     { 
      Console.WriteLine("Hello Task library!"); 
     } 
     static void Main(string[] args) 
     { 
      //method 1 
      //Task.Factory.StartNew(() => { Console.WriteLine("Hello Task library!");}); 

      //method 2 
      //Task task = new Task(new Action(PrintMessage)); 
      //task.Start(); 

      //method3 
      Task task = new Task(delegate { PrintMessage(); }); 
      task.Start(); 
     } 
    } 
} 

我试图让我的控制台应用程序打印消息Hello Task library!。我目前使用下面的method 3。出于某种原因,当我在VS2015上按Ctrl + F5时,该应用程序显示一个空白屏幕,并显示消息Press any key to continue使用C代码启动任务

为什么我的邮件没有打印。

这是因为您没有wait ing为您的任务完成。尝试将task.Wait()添加到方法的末尾,并查看结果应该显示。

更新:如果您正在使用Visual Studio 2017 Update 15.3或更高版本和C#7.1,现在支持asyncMain

可以按如下修改代码:

class Program 
{ 
    private static void PrintMessage() 
    { 
     Console.WriteLine("Hello Task library!"); 
    } 

    static async Task Main() 
    { 
     var task = new Task(PrintMessage); 
     task.Start(); 
     await task; 
    } 
}