【发布时间】:2018-05-16 03:51:24
【问题描述】:
我有这个方法:
public object LongRunningTask()
{
return SomethingThatTakesTooLong();
}
我编写了以下代码,这样我就可以将普通方法转换为异步方法,并且仍然可以得到Exception:
public async Task<object> LongRunningTaskAsync()
{
Exception ex = null;
object ret = await Task.Run(() =>
{
object r = null;
try
{
//The actual body of the method
r = SomethingThatTakesTooLong();
}
catch (Exception e)
{
ex = e;
}
return r;
});
if (ex == null)
return ret;
else
throw ex;
}
当我需要在几个方法中这样做时,我必须复制所有这些代码并只更改中间。
有没有办法做这样的事情?
[SomeAttributeThatDoesThatMagically]
public async Task<object> LongRunningTaskAsync()
{
return SomethingThatTakesTooLong();
}
【问题讨论】:
-
@TheGeneral 但是如果这不是关于异步方法,而只是初始化和终结呢?喜欢:pastebin.com/Hp9tpyTU
-
代替属性,你为什么不写一个应该采用
Action or Func<T>的辅助方法。辅助方法应该使用Task.Run运行它asynchronously。所以所有的调用者类都应该使用辅助方法调用该方法。
标签: c# reflection custom-attributes