0

In Visual Studio I created a new Azure Function project with an HttpTrigger function. This is the code for the function:

  public class DoSomething
  {
     private readonly ILogger<DoSomething> _logger;

     public DoSomething(ILogger<DoSomething> logger)
     {
         _logger = logger;
     }

     [Function("DoSomething")]
     public async Task Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req)
     {
         try
         { 
             _logger.LogInformation("C# HTTP trigger function processed a request.");
             for (int i = 0; i<7; i++)
             {
                 _logger.LogInformation($"Working... {i}");
                 await Task.Delay(1000);
             }
             _logger.LogInformation("Done");
         }
         catch (Exception ex)
         {
             _logger.LogError(ex, "An error occurred.");
         }
         _logger.LogInformation("After Exception");
         return;
     }
 }

The function is called with this console application:

Task.Run(async () =>
{
    using var client = new HttpClient();
    var res = await client.PostAsync("http://localhost:7129/api/DoSomething", null);
});

//Do other stuff
await Task.Delay(4000);

Intentionally my console application closes before the function completes its work. In the function log I get these messages:

[2025-02-06T10:38:32.483Z] C# HTTP trigger function processed a request.
[2025-02-06T10:38:32.485Z] Working... 0
[2025-02-06T10:38:33.486Z] Working... 1
[2025-02-06T10:38:34.491Z] Working... 2
[2025-02-06T10:38:35.497Z] Working... 3
[2025-02-06T10:38:36.508Z] Working... 4
[2025-02-06T10:38:37.518Z] Working... 5
[2025-02-06T10:38:38.533Z] Working... 6
[2025-02-06T10:38:39.549Z] Done
[2025-02-06T10:38:39.552Z] After Exception
[2025-02-06T10:38:39.593Z] Function 'DoSomething', Invocation id '5a240a47-710b-482e-8d43-3a0fdf08c73b': An exception was thrown by the invocation.
[2025-02-06T10:38:39.596Z] Result: Function 'DoSomething', Invocation id '5a240a47-710b-482e-8d43-3a0fdf08c73b': An exception was thrown by the invocation.
Exception: System.InvalidOperationException: An attempt was made to transition a task to a final state when it had already completed.
[2025-02-06T10:38:39.599Z]    at System.Threading.Tasks.TaskCompletionSource`1.SetCanceled(CancellationToken cancellationToken)
[2025-02-06T10:38:39.601Z]    at System.Threading.Tasks.TaskCompletionSource`1.SetCanceled()
[2025-02-06T10:38:39.603Z]    at Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore.ContextReference.CompleteFunction() in D:\a\_work\1\s\extensions\Worker.Extensions.Http.AspNetCore\src\Coordinator\ContextReference.cs:line 59
[2025-02-06T10:38:39.606Z]    at Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore.DefaultHttpCoordinator.CompleteFunctionInvocation(String invocationId) in D:\a\_work\1\s\extensions\Worker.Extensions.Http.AspNetCore\src\Coordinator\DefaultHttpCoordinator.cs:line 55
[2025-02-06T10:38:39.608Z]    at Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore.FunctionsHttpProxyingMiddleware.Invoke(FunctionContext context, FunctionExecutionDelegate next) in D:\a\_work\1\s\extensions\Worker.Extensions.Http.AspNetCore\src\FunctionsMiddleware\FunctionsHttpProxyingMiddleware.cs:line 69
[2025-02-06T10:38:39.612Z]    at Microsoft.Azure.Functions.Worker.FunctionsApplication.InvokeFunctionAsync(FunctionContext context) in D:\a\_work\1\s\src\DotNetWorker.Core\FunctionsApplication.cs:line 77
Stack:    at System.Threading.Tasks.TaskCompletionSource`1.SetCanceled(CancellationToken cancellationToken)
[2025-02-06T10:38:39.614Z]    at System.Threading.Tasks.TaskCompletionSource`1.SetCanceled()
[2025-02-06T10:38:39.616Z]    at Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore.ContextReference.CompleteFunction() in D:\a\_work\1\s\extensions\Worker.Extensions.Http.AspNetCore\src\Coordinator\ContextReference.cs:line 59
[2025-02-06T10:38:39.618Z]    at Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore.DefaultHttpCoordinator.CompleteFunctionInvocation(String invocationId) in D:\a\_work\1\s\extensions\Worker.Extensions.Http.AspNetCore\src\Coordinator\DefaultHttpCoordinator.cs:line 55
[2025-02-06T10:38:39.621Z]    at Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore.FunctionsHttpProxyingMiddleware.Invoke(FunctionContext context, FunctionExecutionDelegate next) in D:\a\_work\1\s\extensions\Worker.Extensions.Http.AspNetCore\src\FunctionsMiddleware\FunctionsHttpProxyingMiddleware.cs:line 69
[2025-02-06T10:38:39.624Z]    at Microsoft.Azure.Functions.Worker.FunctionsApplication.InvokeFunctionAsync(FunctionContext context) in D:\a\_work\1\s\src\DotNetWorker.Core\FunctionsApplication.cs:line 77.
[2025-02-06T10:38:39.678Z] Executed 'Functions.DoSomething' (Failed, Id=5a240a47-710b-482e-8d43-3a0fdf08c73b, Duration=7506ms)
[2025-02-06T10:38:39.680Z] System.Private.CoreLib: Exception while executing function: Functions.DoSomething. Microsoft.Azure.WebJobs.Script.Grpc: Failed to proxy request with ForwarderError: RequestCanceled. System.Net.Http: The operation was canceled. System.Net.Sockets: Unable to read data from the transport connection: Operazione di I/O terminata a causa dell'uscita dal thread oppure della richiesta di un'applicazione.. Operazione di I/O terminata a causa dell'uscita dal thread oppure della richiesta di un'applicazione.

Why does my function code throw an exception?

The console application closes during the “working... X” phase and if there was an exception I was expecting it during the execution of the function code.

Is there any way to avoid the exception without having to wait for the function response from the caller?

Thank you

6
  • Are you getting the same error while running the function? Commented Feb 6 at 11:04
  • I got the exception in the function logs, but after my function code. Commented Feb 6 at 11:12
  • Try the same without wrapping with Task.run(), it worked for me. Commented Feb 6 at 11:37
  • That's not what I wanted to achieve, I was interested in starting the func and continuing my code, without having to wait for the func to end. I know I could use queues, but in my experience starting a queue can take up to many seconds, whereas I would need the func to start immediately. Commented Feb 6 at 11:44
  • Add await in your console code i.e., await Task.Run(async () => Commented Feb 6 at 12:01

2 Answers 2

0

Here, the issue is the console application is closing prematurely before the Azure Function completes the task. To resolve this, you have to ensure that the application stays alive until the function completes.

Add await in the console code which allows the function to finish the task.

Modified Console code as below:

await Task.Run(async () =>
{
    using var client = new HttpClient();
    var res = await client.PostAsync("http://localhost:7158/api/Function1", null);
});
await Task.Delay(4000);

Function.cs:

[Function("Function1")]
public async Task Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req)
{
    try
    {
        _logger.LogInformation("C# HTTP trigger function processed a request.");
        for (int i = 0; i < 7; i++)
        {
            _logger.LogInformation($"Working... {i}");
            await Task.Delay(1000);
        }
        _logger.LogInformation("Done");
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, "An error occurred.");
    }
    _logger.LogInformation("After Exception");
    return;
}

Console Output:

Functions:

        Function1: [GET,POST] http://localhost:7158/api/Function1

For detailed output, run func with --verbose flag.
[2025-02-06T12:00:02.357Z] Host lock lease acquired by instance ID '000000000000000000000000F72731CC'.
[2025-02-06T12:00:06.097Z] Executing 'Functions.Function1' (Reason='This function was programmatically called via the host APIs.', Id=9945e2ab-df32-4e29-b621-9a2e7bd4eee1)
[2025-02-06T12:00:09.087Z] C# HTTP trigger function processed a request.
[2025-02-06T12:00:09.092Z] Working... 0
[2025-02-06T12:00:10.080Z] Working... 1
[2025-02-06T12:00:11.116Z] Working... 2
[2025-02-06T12:00:12.127Z] Working... 3
[2025-02-06T12:00:13.142Z] Working... 4
[2025-02-06T12:00:14.153Z] Working... 5
[2025-02-06T12:00:15.155Z] Working... 6
[2025-02-06T12:00:16.167Z] Done
[2025-02-06T12:00:16.171Z] After Exception
[2025-02-06T12:00:16.463Z] Executed 'Functions.Function1' (Succeeded, Id=9945e2ab-df32-4e29-b621-9a2e7bd4eee1, Duration=10419ms)
Sign up to request clarification or add additional context in comments.

1 Comment

This solves the error but nog the question. The OP does not want to wait: [..]Intentionally my console application closes before the function completes its work.
0

Bear with me please and I just want to share in detail about my test result ,one of the workaround might be using In-process model Azure function.

I didn't reproduce your error in my side with a .Net8 in-process model Azure function. In the meantime, the exception looks like the function attempts to complete a Task that has already been completed. So that I'm deducing this is related to the different behavior for different working model, maybe the Isolated working model requires the connection to keep connected, but I haven't found any document to say why they have such difference.

enter image description here

Next I had a test with .Net 8 Isolated working model Azure function then I got another exception. I'm afraid this is due to library version. I used packages below in my Isolated working model function.

<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="2.0.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.2.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore" Version="2.0.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="2.0.0" />

enter image description here

1 Comment

In the meantime, if the API is not exposed by Azure function, but from an MVC .net core app, no matter the console app is shutdown or not, no matter the API is return response directly or wait for the task execution then return response, API won't throw exception. So that I'm afraid this is an expected behavior because of Isolated working model.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.