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;
}
}
}
本文介绍了一个使用C#实现的任务管理示例,展示了如何利用Task.Run启动后台任务,并通过async/await进行异步操作。文章强调了不要使用断点调试以免中断所有任务。演示了如何并行运行两个异步方法A和B,以及如何根据条件决定是否等待任务B完成。
1246

被折叠的 条评论
为什么被折叠?



