Search code examples
c#async-awaittaskoverloadingmultitasking

How do I overload function to accept both async and synchronized version of callback parameter


public static T SyncVer<T>(Func<T> callback)
{
    using (new LogContext("new logging context"))
    {
        try
        {
            return callback();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);

            throw;
        }
    }
}

public static async Task<T> AsyncVer<T>(Func<Task<T>> callback)
{
    using (new LogContext("new logging context"))
    {
        try
        {
            return await callback();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);

            throw;
        }
    }
}

Please consider the code above. You may see most of the code in both functions is the same. I am searching for a way to group them up by overloading them into one so that I don't need to duplicate the content. Is there a way to take out the similar part of both functions?

Any help provided will be appreciated. Thanks in advance.


Solution

  • I would try something like this:

    public static T SyncVer<T>(Func<T> callback)
    {
        return AsyncVer(() => Task.FromResult(callback())).GetAwaiter().GetResult();
    }