我有一个小实用工具方法,用于在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语句中调用异步方法
你错过了任务返回类型:
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)
| 归档时间: |
|
| 查看次数: |
5796 次 |
| 最近记录: |