NotificationHubClient应该在哪里实例化?

Where Should NotificationHubClient be instantiated?
2021-06-20
  •  译文(汉语)
  •  原文(英语)

我正在试验Azure Notification Bus,我的目标是让WebApi服务在控制器操作触发的特定事件上发送推送通知.

我想知道实例化NotificationHubClient对象的正确位置在哪里.
我假设它可以在控制器中(在发送通知之前),或者可以全局初始化(例如在App_Start中)并在控制器中重新使用.

此示例教程中,NotificationHubClient在控制器中实例化:

public RegisterController()
{
    var cn = "<FULL_SAS_CONNECTION_STRING>";
    hubClient = NotificationHubClient(cn, "<NOTIFICATION_HUB_NAME>");
}

首选方式是什么?

解决过程1

我认为您想在控制器中实例化它.与QueueClient和SubscriptionClient类不同,根据文档,NotificationHubClient的实例成员不能保证是线程安全.这意味着,如果您有一个全局实例,并且在多个请求处理期间使用了它,则它们可能无法很好地交互.

速聊1:
谢谢@Zapnologica.已更正.
解决过程2

好问题!正如MikeWo所说,它没有被记录为线程安全的.但是,如果您查看Azure WebJobs SDK,它们实际上会按(连接字符串,集线器名称)组合缓存客户端.因此,要么Microsoft本身在这里做错了事,要么客户端实际上是线程安全的,并且文档记录很少.

速聊1:
他们很有可能将选项保持打开状态,以使其将来不安全.在这种情况下,这不会是一个重大更改-除非您已假定它是线程安全的,否则它不会.所以要小心

I am experimenting with Azure Notification Bus, and my goal is to have a WebApi service sending push notifications upon specific events triggered by controller actions.

I was wondering where would be the correct place to instantiate the NotificationHubClient object.
I assume it could be either in the controller (right before sending the notification), or instead it could be globally initialized (like in the App_Start) and re-used in the controllers.

In this example tutorial, the NotificationHubClient is instantiated in the controller:

public RegisterController()
{
    var cn = "<FULL_SAS_CONNECTION_STRING>";
    hubClient = NotificationHubClient(cn, "<NOTIFICATION_HUB_NAME>");
}

What would be the preferred way?

Solutions1

I would think that you'd want to instantiate this in the controller. Unlike the QueueClient and SubscriptionClient classes the instance members of the NotificationHubClient are not guaranteed to be Threadsafe according to the docs. This means that if you had a global instance and used it during multiple request processing that they may not interact well.

Talk1:
Thanks @Zapnologica. Corrected.
Solutions2

Good question! As MikeWo states, it is not documented as thread-safe. But if you look at the Azure WebJobs SDK, they actually cache the client per (connection string, hub name) combination. So either Microsoft itself is doing something wrong here, or the client is in fact thread-safe and just poorly documented.

Talk1:
It's quite possible they're keeping the option open to make it thread unsafe in future. In which case it wouldn't be a breaking change - unless you've assumed it is thread safe. So be careful.
转载于:https://stackoverflow.com/questions/18571608/where-should-notificationhubclient-be-instantiated

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入