I am trying to create a SignalR application using the C# 5 async/await features, but whenever the code is run, it will throw an System.InvalidOperationException. Here is the simplest code to reproduce the problem.
public class SampleHub : Hub
{
public Task<string> GetGoogle()
{
var http = new WebClient();
return http.DownloadStringTaskAsync("http://www.google.com");
}
}
Exception details:
An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async=\"true\" %>.
Stack trace:
at System.Web.AspNetSynchronizationContext.OperationStarted()
at System.Net.WebClient.DownloadStringAsync(Uri address, Object userToken)
at System.Net.WebClient.DownloadStringTaskAsync(Uri address)
at System.Net.WebClient.DownloadStringTaskAsync(String address)
On the client side, the Javascript looks like this.
$.connection.hub.start().done(function () {
$('#google').click(function () {
var google = sample.server.getGoogle();
console.log(google);
});
});
What did I do wrong? Are there any workarounds? I am really keen to stick to the async/await patterns in C# if possible at all.
I would try replacing WebClient
with HttpClient
. The DownloadStringTaskAsync
is a kind of "bolt-on" support for async
over the existing EAP methods, and it's the EAP methods that SignalR is objecting to. HttpClient
uses TAP directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With