如何将Async方法作为Action或Func传递
我有一个小实用工具方法,用于在using语句中实例化我的datacontext。 我想在异步方法调用中使用它,但是在方法返回之前处理datacontext。 使用它的正确方法是什么?
这是方法(和重载)
public void Try(Action method) { using (IDataServices client = GetClient()) { method(client); } } public TResult Try(Func method) { using (IDataServices client = GetClient()) { return (TResult)method(client); } }
这是我当前使用它的方式(失败):
Model m = await ClientResolver.Try(async x => await x.GetModelByIDAsync(modelID));
参考:
在using语句中调用异步方法
您错过了任务返回类型:
public async Task Try (Func> method) { using (IDataServices client = GetClient()) { return (TResult)await method(client) } }