1. Task.Run will start to run in background
2. Don't use breakpoint to debug, or all tasks will be interupted.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace SystemTasks
{
class TestTask
{
public static async Task<int> A(int upper)
{
for (int i = 0; i < upper; ++i)
{
await Task.Delay(1000);
Console.WriteLine("A: " + i);
}
return upper;
}
public static async Task<int> B(int upper)
{
for (int i = 0; i < upper; ++i)
{
await Task.Delay(1000);
Console.WriteLine("B: " + i);
}
return upper;
}
public static async Task<int> C()
{
int xx = 0;
var taskb = Task.Run(async () =>
{
Console.WriteLine("Start B:");
int b = await B(10);
Console.WriteLine("End B:");
return b;
});
int a = await A(5);
if (xx == 0)
{// xx == 0, taskb will run in background even if the function has returned.
return a;
}
else
{
await taskb;
return taskb.GetAwaiter().GetResult();
}
}
static void Main()
{
C().GetAwaiter().GetResult();
Thread.Sleep(200000); //If using breakpoint here, all threads will be interupted
return;
}
}
}