.NET Core初览-异步篇
官方说法是提供的异步是语言级别的多线程,基于任务的封装。
这个概念比较简单,额外比较好的一点就是语言级别的 和go写起来能实现差不多的感受。
关于这一点,不是该篇的重点,本文探究的是CPU压榨下的C#提供的异步方案和写法。
写法:
这种写法就在API后面封装,实现同步写法,这一点上和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();
}
}
}