【发布时间】:2016-06-01 16:53:51
【问题描述】:
我正在开发一个通知系统,其中包含服务器端 Intranet 应用程序,该应用程序使用 signalR 将通知发送到客户端,在我的情况下是 Windows 桌面 c# 应用程序。
顺便说一句,这两个应用程序都是使用 SignalR 和 .Net framework 4.5.2 实现的 c# 应用程序。
目前我让我的应用程序连接到服务器以接收通知,我在 windows 桌面应用程序的启动中实现了它。
我希望我的应用程序(Windows 桌面应用程序)尝试连接到服务器,以防在桌面应用程序已经运行时连接因任何原因而丢失。
什么是最好的实现方式
这里是我的 C# 代码,用于将我的应用程序连接到 Intranet 应用程序
public static HubConnection connection;
static void Main()
{
IHubProxy _hub;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
string urlToConnectIntoIntranetServer = @"http://localhost:46412";
connection = new HubConnection(url);
connection.Headers.Add("Securitytoken", "87654321");
_hub = connection.CreateHubProxy("NotificationHub");
_hub.On("broadcastMessage", x => reateToastNotification.CreateToast(x));
connection.Closed += connection_Closed;
connection.Start().Wait();
Application.Run(new Form1());
CreateToastNotification.CreateToast("Hellow world");
}
static void connection_Closed()
{
Pooling(10);
}
private static void Pooling(int i)
{
int nTimes = i;
if (nTimes == 0)
return;
try
{
if (connection!=null)
connection.Start().Wait();
}
catch (AggregateException ae)
{
Thread.Sleep(1000);
Pooling(nTimes - 1);
}
}
【问题讨论】:
-
捕获连接关闭的事件。当它关闭并且您想要重新连接时,请在处理程序中执行此操作。当它关闭时,因为你是例如退出应用程序让它关闭。
-
附带说明一下,您在格式化代码时遇到了一些问题,最好修复这些问题以使其更具可读性
-
谢谢 Ben,我想知道你有什么建议可以使代码更具可读性
-
所以你的意思是把事件 Closed 处理成我的代码 sn-p 中存在的事件? .
-
你已经
connection.Closed += connection_Closed;了。我们能看到connection_Closed的定义吗?那将是自定义处理的好地方,是吗?
标签: c# winforms signalr signalr.client