Skip to content

Instantly share code, notes, and snippets.

@imzjy
Created May 13, 2019 07:28
Show Gist options
  • Save imzjy/ab25309790cfe94397f593e092594031 to your computer and use it in GitHub Desktop.
Save imzjy/ab25309790cfe94397f593e092594031 to your computer and use it in GitHub Desktop.
async and await in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AsyncExplain
{
class Program
{
public static void Main(string[] args)
{
Go();
Console.ReadKey();
}
static async void Go()
{
var sumTask = ComputeServiceAync(3, 5);
Console.WriteLine("Hello World!");
//等待返回的task执行完成,因为我们需要用他的结果(Thread Block在这里,直到完成任务return结果
var sum = await sumTask;
Console.WriteLine(sum);
}
static Task<int> ComputeServiceAync (int a, int b)
{
var t = Task.Factory.StartNew<int>(() => {
Thread.Sleep(10000);
return a + b;
});
//T代表一个正在执行的Task
return t;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment