SignalR - 如何执行枢纽异步任务? [英] SignalR - How to perform async Task in hub?

查看:372
本文介绍了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.

这篇关于SignalR - 如何执行枢纽异步任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆