官方将 C# 的异步定义为语言级别的多线程,底层基于任务(Task)封装。这个概念本身并不复杂,亮点在于它是语言内置支持,写起来和 Go 的协程风格颇为相近。
不过语言层面的对比不是本文的重点。本文聚焦于 CPU 密集场景下,C# 异步方案的具体写法与使用方式。
同步调用包装异步操作
下面这种写法把异步逻辑封装在内部方法里,对外暴露同步接口,使调用方无需感知异步细节,风格上与 Go 的同步写法非常接近。
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net.Http;
namespace ConsoleApp2
{
class RedisMgr
{
int WorkerFunc(int x)
{
//can do sync opt in this func
return x * x * x * x * x * x * MathF.Sign(0.1f);
}
private async Task<int> GetIntInternal(string key)
{
var task = Task.Run(() => WorkerFunc(2));
var result = await task;
return result;
}
public int GetInt(string key)
{
return this.GetIntInternal(key).Result;
}
}
class Program
{
static void Main(string[] args)
{
RedisMgr xx = new RedisMgr();
var val = xx.GetInt("redis_key_1");//async operation
Console.WriteLine(val);
Console.ReadLine();
}
}
}