我如何通过异步方法,操作或FUNC。 [英] How do I pass async method as Action or Func
本文介绍了我如何通过异步方法,操作或FUNC。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有我用实例化一个using语句里面我的DataContext一点实用方法。我想用一个异步方法调用但是在DataContext在方法返回前处理使用。什么是使用正确的方法?
I have a little utility method I use to instantiate my datacontext inside a using statement. I want to use this with an async method call however the datacontext is disposed before the method returns. What is the correct way to use this?
下面是方法(和重载)
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);
}
}
下面是如何,我currenty使用它(失败):
Here is how I am currenty using it (fails):
Model m = await ClientResolver.Try(async x => await x.GetModelByIDAsync(modelID));
参考:结果
<一href=\"http://stackoverflow.com/questions/20431528/calling-asynchronous-method-in-using-statement\">Calling在using语句异步方法
推荐答案
您错过任务返回类型:
public async Task<TResult> Try<TResult>(Func<IDataServices, Task<TResult>> method)
{
using (IDataServices client = GetClient())
{
return (TResult)await method(client)
}
}
这篇关于我如何通过异步方法,操作或FUNC。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文