如何在.NET中装饰(时间)任务?

And*_*nea 3 .net c# asynchronous task task-parallel-library

我有类似的服务:

public class Service : IService
{
    public Task<string> GetData()
    {
        var client = new HttpClient();
        var str = client.GetStringAsync("http://www.example.com");
        return str;
    }
    //...
}
Run Code Online (Sandbox Code Playgroud)

现在,使用装饰器模式我想要计时这个方法

public class TimedService : IService
{
    private readonly IService _service;

    public TimedService(IService service)
    {
        _service = service;
    }

    public Task<string> GetData()
    {
        using(var timer = new TimerContext())
            return _service.GetData();
    }
}        
Run Code Online (Sandbox Code Playgroud)

TimerContext构建之后的开始计时并将其停止处理并将其发布到某种日志中,而不需要返回测量的时间.

现在使用上述方法不会计算任务的实际执行时间,而只是创建和检索Task实例.

如何Task从TimedService 返回一个,当运行时,它将启动计时器,执行原始Task(从真实Service类)并处理计时器?

Ser*_*rvy 8

制作方法asyncawaitTask.

public async Task<string> GetData()
{
    using(var timer = new TimerContext())
        return await _service.GetData();
}
Run Code Online (Sandbox Code Playgroud)

现在timerGetData完成时处理,而不是在它启动后立即处理.