David Pilkington
David Pilkington

Reputation: 13620

Sending data to EventHub from Asp.Net site

I have an Azure EventHub that I send data to. If I use the following code in a console application (framework 4.6.1), it runs perfectly.

        eventHubClient = EventHubClient.CreateFromConnectionString(myConnString);

        Console.WriteLine("Client Created");

        var sender = eventHubClient.CreatePartitionSender("1");

        var message = $"Message";

        Console.WriteLine($"Sending message: {message}");
        var eventData = new EventData(Encoding.UTF8.GetBytes(message));

        if (!sender.SendAsync(eventData).Wait(TimeSpan.FromMilliseconds(10000)) )
        {
           int a = 0;
        }

However, if I put it in an Asp.Net application (targeting framework 4.6.1) either running in IIS-Express or IIS, it times out every time.

What am I missing here?

Upvotes: 2

Views: 463

Answers (1)

David Pilkington
David Pilkington

Reputation: 13620

It seems that when you call use an async method in a non-async context in an Asp.Net application, it causes some sorted of dead-lock.

In my case, I need to know if it has timed out so I couldn't just leave it to run asynchronously and there was work that I needed done after the async call was completed as well as if it failed.

This is what I did

Task.Run(() =>
{
    if (!sender.SendAsync(eventData).Wait(TimeSpan.FromMilliseconds(10000)) )
        {
           int a = 0;
        }
});

This allows me to handle both timeouts as well as success. Unfortunately it was not an option to make the entire call stack async so using await was out of the question.

TL;DR : Calling .Wait() in an ASP.NET application can cause a deadlock.

Upvotes: 1

Related Questions