问题
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();
}
}
}
I am trying to get my Console app to print the message Hello Task library!
. I am currently using method 3
below. For some reason the app shows a blank screen with the message Press any key to continue
when I press Ctrl + F5
on VS2015.
Why is my message not getting printed.
回答1:
This is because you are not wait
ing for your task to complete. Try add task.Wait()
to the end of your method and see the result should be displayed.
Update: If you are using Visual Studio 2017 Update 15.3 or above and C# 7.1, there is support for async
Main
now.
You can modify your code as follows:
class Program
{
private static void PrintMessage()
{
Console.WriteLine("Hello Task library!");
}
static async Task Main()
{
var task = new Task(PrintMessage);
task.Start();
await task;
}
}
来源:https://stackoverflow.com/questions/46677220/starting-a-task-using-delegate-in-c-sharp