我写了这个小应用程序。出于某种原因,当我运行这个程序时,我无法打印“Hello from a thread”。但是,如果我调试它并在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");
}
}
}
答案 0 :(得分:11)
在您看到输出之前,您确定该程序没有关闭吗?因为这对我来说很好。
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");
}
}
}
编辑:添加了我在回复时写的评论,包括我为什么没有打印文本的原因。
它或者是因为应用程序在线程可以将字符串输出到屏幕之前关闭。您也可能无法看到它,因为它会立即关闭。无论哪种方式,它与断点一起工作的原因是因为你让应用程序保持更长时间。
答案 1 :(得分:2)
试试这个。
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");
}
}
}