Andrei Rînea Andrei Rînea - 15 days ago 6
C# Question

How do I decorate (time) a Task in .NET?

I have a service similar to:

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


Now, using the decorator pattern I want to time this method

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


The
TimerContext
starts timing after its constructed and stops it on disposal and publishes it into some kind of log.

Now using the above approach does not time the real execution time of the task but the mere creation and retrieval of the Task instance.

How do I return a
Task
from the TimedService which, when run, will start the timer, execute the original
Task
(from the real
Service
class) and the dispose the timer?

Answer

Make the method async and await the Task.

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

Now timer will be disposed when GetData has completed, rather than as soon as it has been started.

Comments