【问题标题】:SignalR .NET client: subsequent method Invoke with same connection openedSignalR .NET 客户端:打开相同连接的后续方法调用
【发布时间】:2014-07-29 07:58:31
【问题描述】:

我有一个 .NET 客户端应用程序,连接到使用 .net mvc5 webapp 托管的 SignalR Hub。客户端应用程序的主要例程:

int num1 = _myService.GetSomeHubMethod();
int num2 = _myService.GetSomeOtherHubMethod();
...

其中 _myService 是该类的一个实例:

public class MyService
{
    ...
    private HubConnection connection;
    private IHubProxy hubProxy;
    ...

    public MyService()
    {
         ...
         if (BASE_SITE_URL == null)
            BASE_SITE_URL = ConfigurationManager.AppSettings["BASE_SITE_URL"].ToString();
        if (connection == null)
            connection = new HubConnection(BASE_SITE_URL);
        if (hubProxy == null)
            hubProxy = connection.CreateHubProxy("MyHub");

        connection.Start().Wait();
    }

    ...

    public int GetSomeHubMethod()
    {
        //connection.Start().Wait();

        var t = hubProxy.Invoke<int>("SomeHubMethod");

        int result = t.Result;

        //connection.Stop();

        return result;
    }

    public int GetSomeOtherHubMethod()
    {
        //connection.Start().Wait();

        var t = hubProxy.Invoke<int>("SomeOtherHubMethod");

        int result = t.Result;

        //connection.Stop();

        return result;
    }

}

SignalR 集线器(服务器端)中的两个集线器方法是:

public class MyHub : Hub
{
    ...
    public int SomeHubMethod()
    { return 1; }

    public int SomeOtherHubMethod()
    { return 2; }        

}

问题是:第一个调用被正确评估,但第二个调用“挂起”在 int 结果 = t.Result; 线。特别是 t.Status 是“WaitingForActivation”。

如果我在主例程中切换两个调用的顺序,第一个被执行,第二个“挂起”。

注意:如果我在两个方法中启动和停止连接(见注释行),而不是在 MyService 的构造函数中调用 connection.Start().Wait(),它可以完美运行,但需要太多时间停止和开始。

感谢大家的帮助!

【问题讨论】:

  • 我无法在 SignalR 2.0.3 上重现此内容,您使用的是什么版本?
  • @小红同,2.0.3。你能调用这两个方法吗?

标签: signalr signalr-hub signalr.client


【解决方案1】:

好的,看来这是一个僵局。我不得不这样修改方法:

public async Task<int> SomeHubMethod()
{
    return await Task.FromResult<int>(1);
}

...

public async Task<int> GetSomeHubMethod()
{
    return await chatHubProxy.Invoke<int>("SomeHubMethod");
}

...

int num1 = await _myService.GetSomeHubMethod();

好吧,我承认我还有很多工作要做异步的东西......

【讨论】:

  • 不'等待_myService.GetSomeHubMethod();'返回一个任务,而不是一个 int?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-06
  • 2021-12-05
  • 2012-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多