markjprice / apps-services-net8

Repository for the Packt Publishing book titled "Apps and Services with .NET 8" by Mark J. Price
119 stars 55 forks source link

Azure function requires async or AllowSynchronousIO #10

Closed Pip1987 closed 6 months ago

Pip1987 commented 9 months ago

I got the following error:

[2024-02-19T22:04:57.896Z] Function 'NumbersToWordsFunction', Invocation id '1c7e2c25-32c6-4027-b30b-f29216597cfa': An exception was thrown by the invocation.
[2024-02-19T22:04:57.897Z] Result: Function 'NumbersToWordsFunction', Invocation id '1c7e2c25-32c6-4027-b30b-f29216597cfa': An exception was thrown by the invocation.
Exception: System.InvalidOperationException: Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true instead.
...

Changing the following WriteString to WriteStringAsync fixed the issue.

        if (long.TryParse(amount, out long number))
        {
            response = req.CreateResponse(System.Net.HttpStatusCode.OK);
            //response.WriteString(number.ToWords());
            response.WriteStringAsync(number.ToWords());
        }
        else
        {
            response = req.CreateResponse(
                System.Net.HttpStatusCode.BadRequest);

            //response.WriteString($"Failed to parse: {amount}");
            response.WriteStringAsync($"Failed to parse: {amount}");
        }

or adding the following lines to program.cs (this option was found on stack overflow. https://stackoverflow.com/a/55196057

        services.Configure<KestrelServerOptions>(options =>
        {
            options.AllowSynchronousIO = true;
        });
markjprice commented 8 months ago

I cannot reproduce this issue.

DocVD commented 6 months ago

I had the same issue. I used option#2 above and it works fine now.

Your examples, Mark, have been spot on throughout my going through the book - except for the gotchas that have already been discussed. I have really enjoyed the ability to move forward constantly.

markjprice commented 6 months ago

Thanks, DocVD. I'm happy to hear (most) of my code works as described in the book. ;-)

I've added an errata item for this in case anyone else has the same issue. https://github.com/markjprice/apps-services-net8/blob/main/docs/errata/errata.md#page-449---implementing-a-simple-function

I will also make time to look at this again over the summer. Right now I am neck-deep in Tools and Skills for .NET 8 work.