是否可以使用方法属性来更改此方法的运行方式?

时间:2018-05-16 03:51:25

标签: c# reflection custom-attributes

我有这个方法:

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();
}

1 个答案:

答案 0 :(得分:1)

属性通常是元数据,尽管可以定义可以执行的属性(例如WCF中的安全行为)但是,必须首先查找它。你的属性不会神奇地运行。

我怀疑你可能不得不使用动态代理。

看看WCF如何为创意做点事。

相关问题