您如何实现异步操作委托方法? [英] How do you implement an async action delegate method?

查看:28
本文介绍了您如何实现异步操作委托方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?
}

推荐答案

Actionasync 等价物是 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;
}

这篇关于您如何实现异步操作委托方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆