c# - 通知 SignalR 客户端 IIS 重启/关闭

标签 c# .net iis signalr

我有一个 SignalR 服务器(一个 Web 应用程序)和一个客户端(一个控制台应用程序)。

我希望我的客户端在我的服务器的 IIS 重新启动/关闭或服务器简单地重新启动/关闭时得到通知。

这可能吗?

最佳答案

你可以这样做

var connection = new HubConnection(hubUrl);
if (configureConnection != null)
    configureConnection(connection);

var proxy = connection.CreateHubProxy("EventAggregatorProxyHub");
connection.Reconnected += reconnected;

https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/blob/master/SignalR.EventAggregatorProxy.Client.DotNet/Bootstrap/Factories/HubProxyFactory.cs#L17

其他事件是

  • Reconnecting - 在连接关闭后尝试重新连接时触发
  • 关闭 - 连接断开时触发

更新:

Closed 将在重新连接失败时调用(当 IIS 关闭的时间超过重新连接超时所接受的时间时)。

这意味着您应该使用 connection.Start() 从 Close 事件重新连接,当它失败时,Closed 事件将被再次调用,并且可以使用 connection.Start()< 重试.

这是一个使用我的代码的示例,它会在应用程序启动时 IIS 关闭和运行时关闭

public class HubProxyFactory : IHubProxyFactory
{
    public IHubProxy Create(string hubUrl, Action<IHubConnection> configureConnection, Action<IHubProxy> onStarted, Action reconnected, Action<Exception> faulted, Action connected)
    {
        var connection = new HubConnection(hubUrl);
        if (configureConnection != null)
            configureConnection(connection);

        var proxy = connection.CreateHubProxy("EventAggregatorProxyHub");
        connection.Reconnected += reconnected;
        connection.Error += faulted;

        var isConnected = false;

        Action start = () =>
        {
            Task.Factory.StartNew(() =>
            {
                try
                {
                    connection.Start().Wait();
                    if(isConnected)
                        reconnected();
                    else
                    {
                        isConnected = true;
                        onStarted(proxy);
                        connected();
                    }
                }
                catch(Exception ex)
                {
                    faulted(ex);
                }
            });
        };

        connection.Closed += start;

        start();

        return proxy;
    }
}

关于c# - 通知 SignalR 客户端 IIS 重启/关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30328863/

相关文章:

asp.net - 为什么从iis调用XMLRPC时fiddler没有捕获请求?

.net - msxml6.dll 错误 '80072ee2' 操作超时

C#:枚举值可以保存为设置吗?

c# - 是否存在将我的泛型方法限制为数字类型的约束?

.Net Core HttpClientFactory 配置 HttpClientHandler

c# - 在 WPF .NET Framework 中使用自定义任务管理器时,如何防止进程重复?

asp.net - 为什么 IIS 在第一次访问时很慢,但之后会更快?

c# - Linq distinct 无法正常工作

c# - 我的 C# Entity Frameworks 项目闹鬼了吗?

c# - Google Sheets API,在 C# 中为用户获取电子表格