using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
var outer = Task.Factory.StartNew(OuterMethod);
outer.Wait();
Console.WriteLine("Console app is stopping");
}
static void OuterMethod()
{
Console.WriteLine("Outer method starting...");
var inner = Task.Factory.StartNew(InnerMethod);
Console.WriteLine("Outer methed finished");
}
static void InnerMethod()
{
Console.WriteLine("Inner method starting...");
Thread.Sleep(2000);
Console.WriteLine("Inner method finished");
}
}
}
运行,OutMethod执行完毕,但InnerMethod没有执行完毕
修改启动InnerMethod的任务方法,使其和parent关联
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
var outer = Task.Factory.StartNew(OuterMethod);
outer.Wait();
Console.WriteLine("Console app is stopping");
}
static void OuterMethod()
{
Console.WriteLine("Outer method starting...");
var inner = Task.Factory.StartNew(InnerMethod,TaskCreationOptions.AttachedToParent);
Console.WriteLine("Outer methed finished");
}
static void InnerMethod()
{
Console.WriteLine("Inner method starting...");
Thread.Sleep(2000);
Console.WriteLine("Inner method finished");
}
}
}
OuterMethod和InnerMethod都执行完毕后,程序才会结束



