当前位置:网站首页>无需编码,自动实现“异步 Request-Reply”模式
无需编码,自动实现“异步 Request-Reply”模式
2022-07-24 02:20:00 【dotNET跨平台】
前言
上次,我们虽然用代码实现了“异步 Request-Reply 模式”,但是需要为每一个长时间操作 API 实现一个对应的 AsyncXXX 操作。
其实,可以尝试用 Source Generators 减少这种重复性劳动。
实现思路
Controller 类必须是
partial,这样才能为它额外增加新方法;为每个长时间操作 API 声明一个 AsyncMethodAttribute,这样 Source Generators 才知道为谁实现对应的同步操作;
遍历所有声明了 AsyncMethodAttribute 的方法,为其编写实现方法。
具体代码
1.添加 AsyncMethodAttribute
向待编译项目加入 AsyncMethodAttribute 代码:
const string asyncMethodAttributeText = @"using System;
namespace AsyncMethodGenerator
{
public sealed class AsyncMethodAttribute : Attribute
{
public AsyncMethodAttribute()
{
}
}
}
";
context.AddSource("AsyncMethodAttribute", SourceText.From(asyncMethodAttributeText, Encoding.UTF8));2.遍历 AsyncMethodAttribute 声明方法
找到声明了 AsyncMethodAttribute 的所有方法:
private string GenerateMethods(SyntaxList<MemberDeclarationSyntax> members)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (var member in members)
{
if(member is MethodDeclarationSyntax method && HasAsyncMethodAttribute(method))
{
stringBuilder.Append(GenerateAsyncMethod(method));
}
}
return stringBuilder.ToString();
}
private bool HasAsyncMethodAttribute(MethodDeclarationSyntax method)
{
var hasAttribute = false;
foreach (var attributeList in method.AttributeLists)
{
foreach (var attribute in attributeList.Attributes)
{
if (attribute.Name.ToString().Equals("AsyncMethod"))
{
hasAttribute = true;
}
}
}
return hasAttribute;
}3.生成 AsyncMethod 代码
根据原方法定义,生成 AsyncMethod 方法:
private string GenerateAsyncMethod(MethodDeclarationSyntax method)
{
var stringBuilder = new StringBuilder();
foreach (var attributeList in method.AttributeLists)
{
foreach (var attribute in attributeList.Attributes)
{
if (attribute.Name.ToString().Equals("Route"))
{
stringBuilder.Append([email protected]"[Route(""async/{attribute.ArgumentList.Arguments[0].ToString().Trim('"')}"")]");
}
else
{
stringBuilder.Append($"[{attribute}]");
stringBuilder.Append("\r\n");
}
}
}
stringBuilder.Append($"public async Task<IActionResult> Async{method.Identifier} ");
stringBuilder.Append($"({method.ParameterList.Parameters})");
stringBuilder.Append("\r\n");
stringBuilder.Append([email protected]"
{
{
string id = Guid.NewGuid().ToString();
string responseValue = [email protected]""/status/{
{id}}"";
_cache.SetString(id, responseValue);
Task.Factory.StartNew(() =>
{
{
var result = {GenerateCallingMethod(method)}.Result;
_cache.SetString(id + ""_result"", JsonConvert.SerializeObject(result));
}});
return Accepted(responseValue);
}}
");
return stringBuilder.ToString();
}4.使用
现在,就可以在目标项目中使用 AsyncMethod 方法了:
[ApiController]
[Route("[controller]")]
public partial class WeatherForecastController : ControllerBase
{
...
[HttpGet]
[Route("get")]
[AsyncMethod]
public async Task<IEnumerable<WeatherForecast>> Get()
{
...
}
}注意 WeatherForecastController 是 partial class
结论
有了 Source Generators,可以让编译器帮我们自动实现“异步 Request-Reply 模式”了!
想了解更多内容,请关注我的个人公众号”My IO“
边栏推荐
- The communication principle between native components, applets and clients, and the operation principle of video, map, canvas, picker, etc
- Codeworks 5 questions per day (average 1500) - day 23
- wallys/WiFi6 MiniPCIe Module 2T2R2 × 2.4GHz 2x5GHz MT7915 MT7975
- Phpcms realizes product multi condition screening function
- Digicert code signing certificate
- Give me five minutes, give you a "cloud"
- 深入理解微信小程序的底层框架(二)组件系统、Exparser
- 使用第三方账号登录
- Performance test of ArrayList and LinkedList insertion based on jmh
- Ardunio - ULN2003 drive board and DC motor fan - control fan speed
猜你喜欢

Loadrunner12 installation, recording the first script and the proxy server did not respond to the solution

jmeter+influxdb+grafana压测实时监控平台搭建

Network protocol details: UDP

145-keep-alive的初步使用

小散量化炒股记|基于多任务爬虫技术, 实现A股实时行情Level1采样

MySQL---four JDBC
![[C language] preprocessing details](/img/c3/861165ce20c135f4feedee1f112261.png)
[C language] preprocessing details

以科技传递温度,vivo守护生物多样性之美
深入理解微信小程序的底层框架(二)组件系统、Exparser

Cinq ans de contact avec près d'une centaine de patrons, en tant que chasseur de têtes, j'a i découvert que le secret de la promotion n'est que quatre mots
随机推荐
Webshell management tool and its traffic characteristics analysis
5年接触近百位老板,身为猎头的我,发现升职的秘密不过4个字
jmeter+influxdb+grafana压测实时监控平台搭建
On the possibility and limitation of defi in the metauniverse
Phpcms realizes product multi condition screening function
[hiflow] regularly send Tencent cloud SMS sending group
Seatunnel architecture
145-keep-alive的初步使用
输入cnpm -v出现cnpm : 无法加载文件 C:\Users\19457\AppData\Roaming\npm\cnpm.ps1,因为在此系统上禁止运行脚本。
Ggplot2 displays png
Qml- use listview to build a three-level treeview architecture
About rapidssl certificate
One year after graduation, I gave up the internship opportunity and taught myself software testing at home. The internship of my classmates has just ended. I have become a 12K monthly salary testing e
杂志特稿:元宇宙将重塑我们的生活,我们要确保它变得更好
通过Arduino IDE向闪存文件系统上传文件
Preliminary use of 145 keep alive
J. Serval and essay (tarjan finds topological order)
[untitled]
MySQL---four JDBC
Wallys/PD-60 802.3AT Input Output802.3AT/AT 85% Efficiency 10/100/1000M GE Surge Protection