Starting a task using delegate in C#

∥☆過路亽.° 提交于 2021-02-08 09:53:57

问题


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 waiting 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!