This is a mirror of official site: http://jasper-net.blogspot.com/

Awaitable task progress reporting

| Sunday, September 23, 2012
In my previous Task.WhileAll post I had a very fishy piece of code in sample where I put a Thread to sleep in order to give enough time for async composition to complete so the test could pass.

Well, every time I use a Thread.Sleep anywhere I know it is a bad thing so I've decided to get rid of it.

IProgressAsync<T>

The problem is related to the fact that IProgress<T> interface defines a void handler which can't be awaited and thus it ruins composition.

That's why I decided to define my own "true async" version of the interface which looks has the same report method but returning a Task I can await.

namespace WhileAllTests
{
    using System.Threading.Tasks;
 
    public interface IProgressAsync<in T>
    {
        Task ReportAsync(T value);
    }
}

Having a async version of reporting is VERY useful when the subscriber itself is awaiting further calls. I could get that with async void but using async void IMHO always turns to be bad solution so I choose to use the Task returning signature even I need a custom made interface for that.

And here's the implementation

using System;
using System.Threading.Tasks;
 
public class ProgressAsync<T> : IProgressAsync<T>
{
    private readonly Func<T, Task> handler;
 
    public ProgressAsync(Func<T, Task> handler)
    {
        this.handler = handler;
    }
 
    public async Task ReportAsync(T value)
    {
        await this.handler.Invoke(value);
    }
}

Read more: .NET AND ME
QR: Inline image 1

Posted via email from Jasper-net

0 comments: