Task.Factory.StartNew()对我不起作用

本文关键字:不起作用 Factory StartNew Task | 更新日期: 2023-09-27 18:19:48

我编写了这个小应用程序。由于某种原因,当我运行这个程序时,我无法打印"来自线程的Hello"。但是,如果我调试它并在Do()方法中放置断点,它就会打印出来。

有什么想法吗?

using System;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Task.Factory.StartNew(Do);
        }
        private static void Do()
        {
            Console.WriteLine("Hello from a thread");
        }
    }
}

Task.Factory.StartNew()对我不起作用

您确定在看到输出之前程序没有关闭吗?因为这对我来说很好。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
    class Program
    {
        private static void Main(string[] args)
        {
            Task.Factory.StartNew(Do);
            Console.Read();
        }
        private static void Do()
        {
            Console.WriteLine("Hello from a thread");
        }
    }
}

编辑:添加了我对此所写的评论,包括我对为什么没有打印文本的推理

这要么是因为应用程序在线程有可能将字符串输出到屏幕之前就关闭了。也有可能你根本看不到它,因为它马上就关闭了。无论哪种方式,它使用断点的原因都是因为您可以延长应用程序的生存时间。

试试这个。

using System;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Task.Factory.StartNew(Do);
            Console.ReadKey();
        }
        static void Do()
        {
            Console.WriteLine("Hello from a thread");
        }
    }
}