您的位置:首页 > 编程语言 > C#

c# task run in background

2017-02-23 15:36 507 查看
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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: