Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding duplicate methods for Task and Task<T>

Tags:

c#

.net

task

I have some logic for Task and Task<T>. Is there any way to avoid duplicating code ?

My current code is following:

public async Task<SocialNetworkUserInfo> GetMe()
{
    return await WrapException(() => new SocialNetworkUserInfo());
}

public async Task AuthenticateAsync()
{
    await WrapException(() => _facebook.Authenticate());
}

public async Task<T> WrapException<T>(Func<Task<T>> task)
{
    try
    {
        return await task();
    }
    catch (FacebookNoInternetException ex)
    {
        throw new NoResponseException(ex.Message, ex, true);
    }
    catch (FacebookException ex)
    {
        throw new SocialNetworkException("Social network call failed", ex);
    }
}

public async Task WrapException(Func<Task> task)
{
    try
    {
        await task();
    }
    catch (FacebookNoInternetException ex)
    {
        throw new NoResponseException(ex.Message, ex, true);
    }
    catch (FacebookException ex)
    {
        throw new SocialNetworkException("Social network call failed", ex);
    }
}
like image 523
Grigory Avatar asked May 29 '14 16:05

Grigory


2 Answers

You can make the Task overload call the other one, and return a dummy value.

public async Task WrapException(Func<Task> task)
{
    await WrapException<object>(async () => {
        await task();
        return null;
    });
}

Or, since the async keyword is unnecessary here:

public Task WrapException(Func<Task> task)
{
    return WrapException<object>(async () => {
        await task();
        return null;
    });
}
like image 58
Tim S. Avatar answered Oct 11 '22 11:10

Tim S.


Assuming that Func does not itself throw, the following would work.

public async Task<T> WrapException<T>(Func<Task<T>> task)
{
    var actualTask = task();
    await WrapException((Task)actualTask);
    return actualTask.Result;
}

We know that Result won't block or throw since WrapException ensured it ran to completion.

like image 24
Guvante Avatar answered Oct 11 '22 11:10

Guvante