如何将Async方法作为Action或Func传递

Sam*_*Sam 3 c# async-await

我有一个小实用工具方法,用于在using语句中实例化我的datacontext.我想在异步方法调用中使用它,但是在方法返回之前处理datacontext.使用它的正确方法是什么?

这是方法(和重载)

    public void Try(Action<IDataServices> method)
    {
        using (IDataServices client = GetClient())
        {
            method(client);
        }
    }

    public TResult Try<TResult>(Func<IDataServices, TResult> method)
    {
        using (IDataServices client = GetClient())
        {
            return (TResult)method(client);
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是我当前使用它的方式(失败):

    Model m = await ClientResolver.Try(async x => await x.GetModelByIDAsync(modelID));
Run Code Online (Sandbox Code Playgroud)

参考:
在using语句中调用异步方法

rdu*_*com 9

你错过了任务返回类型:

public async Task<TResult> Try<TResult>(Func<IDataServices, Task<TResult>> method)
{
    using (IDataServices client = GetClient())
    {
        return (TResult)await method(client)
    }
}
Run Code Online (Sandbox Code Playgroud)