SignalR - 如何执行枢纽异步任务?

SignalR  - 如何执行枢纽异步任务?

问题描述:

我想创建一个使用C#5异步/等待功能SignalR应用程序,但每当运行code,它会抛出一个System.InvalidOperationException。这是最简单的code重现该问题。

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");
    }
}

异常详细信息:

这是异步操作不能在这个时间开始。异步操作只能在异步处理程序或模块内或在在页面生命周期的某些事件开始。如果在执行一个页面出现了这种异常,保证页面被标记为LT;%@页面异步= \\真正\\%>

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\" %>.

堆栈跟踪:

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)

在客户端,JavaScript的看起来是这样的。

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);
    });
});

我做了什么错?是否有任何变通办法?我真的很渴望能坚持到异步/待机模式在C#如果可能的话都没有。

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.

我会尝试更换 Web客户端的HttpClient 。在 DownloadStringTaskAsync 是一种栓上的支持异步在现有的EAP 方法,以及它是SignalR是反对的EAP方法。 的HttpClient 直接

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.