您如何实现异步操作委托方法?

编程入门 行业动态 更新时间:2024-10-10 06:22:10
本文介绍了您如何实现异步操作委托方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在学习 Web API 堆栈,并尝试以Result"的形式封装所有数据;带有Success 和ErrorCodes 等参数的对象.

I am learning the Web API stack and I am trying to encapsulate all data in the form of a "Result" object with parameters such as Success and ErrorCodes.

然而,不同的方法会产生不同的结果和错误代码,但结果对象通常会以相同的方式实例化.

Different methods however, would produce different results and error codes but the result object would generally be instantiated the same way.

为了节省一些时间并了解有关 C# 中 async/await 功能的更多信息,我试图将我的 Web API 操作的所有方法主体包装在一个异步动作委托,但陷入了困境...

To save some time and also to learn more about async/await capabilities in C#, I am trying to wrap all the method bodies of my web API actions in an asynchronous action delegate but got caught in a bit of a snag...

public class Result { public bool Success { get; set; } public List<int> ErrorCodes{ get; set; } } public async Task<Result> GetResultAsync() { return await DoSomethingAsync<Result>(result => { // Do something here result.Success = true; if (SomethingIsTrue) { result.ErrorCodes.Add(404); result.Success = false; } } }

我想编写一个对 Result 对象执行操作并返回它的方法.通常通过同步方法它会

I want to write a method that performs an action on a Result object and return it. Normally through synchronous methods it would be

public T DoSomethingAsync<T>(Action<T> resultBody) where T : Result, new() { T result = new T(); resultBody(result); return result; }

但是如何使用 async/await 将此方法转换为异步方法?

But how do I transform this method into an asynchronous method using async/await?

这是我尝试过的:

public async Task<T> DoSomethingAsync<T>(Action<T, Task> resultBody) where T: Result, new() { // But I don't know what do do from here. // What do I await? }

推荐答案

Action 的 async 等价物是 Func,所以我相信这就是你要找的:

The async equivalent of Action<T> is Func<T, Task>, so I believe this is what you're looking for:

public async Task<T> DoSomethingAsync<T>(Func<T, Task> resultBody) where T : Result, new() { T result = new T(); await resultBody(result); return result; }

更多推荐

您如何实现异步操作委托方法?

本文发布于:2023-11-23 07:29:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1620607.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何实现   操作   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!