How to solve: Anonymous function converted to a void returning delegate cannot return a value

77 Views Asked by At

I am trying to implement semaphore slim for a set of tasks that are meant to request some data to an external API. The data might have different formats, so the plan is to return HttpResponseMessage, so the converter (JSON converter) will deal with it. However I am getting the mentioned error on the return and I have no idea what to do:

tasks.Add(
Task<HttpResponseMessage>.Run(() =>
{
    semaphoreSlim.WaitAsync();
    
    try{
        return (SetupRequestAsync(request, HttpMethod.Get));
    }
    catch (Exception ex) { throw ex; }
    finally { semaphoreSlim.Release();  }
    
}, cancelTok
));

cancelTok is a cancellation token that is meant to stop creating threads once we got a valid result from server through SetupRequestAsync (which is meant to return an HttpResponseMessage).

Edit: return has an underline in red, marking that there is an error, when I hover over, the error is shown.

error

1

There are 1 best solutions below

0
Charlieface On

You need to make the lambda async and then await the calls inside it. Do not swallow and rethrow exceptions, all it does is wipe the stack trace.

var task = Task.Run(async () =>
{
    try
    {
        await semaphoreSlim.WaitAsync(cancelTok);
        return await SetupRequestAsync(request, HttpMethod.Get);
    }
    finally
    {
        semaphoreSlim.Release();
    }
}, cancelTok);
tasks.Add(task);