我遇到了同样的问题。我的侦听器在服务的主线程之前启动。我将需要启动的侦听器列表排队,然后在主线程中尽早激活它们。结果,所有传入的消息都能够被处理并放入适当的可靠存储中。我的简单解决方案(这是一个服务总线监听器):
public Task<string> OpenAsync (CancellationToken cancellationToken)
{
string uri;
Start ();
uri = "<your endpoint here>";
return Task.FromResult (uri);
}
public static object lockOperations = new object ();
public static bool operationsStarted = false;
public static List<ClientAuthorizationBusCommunicationListener> pendingStarts = new List<ClientAuthorizationBusCommunicationListener> ();
public static void StartOperations ()
{
lock (lockOperations)
{
if (!operationsStarted)
{
foreach (ClientAuthorizationBusCommunicationListener listener in pendingStarts)
{
listener.DoStart ();
}
operationsStarted = true;
}
}
}
private static void QueueStart (ClientAuthorizationBusCommunicationListener listener)
{
lock (lockOperations)
{
if (operationsStarted)
{
listener.DoStart ();
}
else
{
pendingStarts.Add (listener);
}
}
}
private void Start ()
{
QueueStart (this);
}
private void DoStart ()
{
ServiceBus.WatchStatusChanges (HandleStatusMessage,
this.clientId,
out this.subscription);
}
=========================
在主线程中,您调用该函数来启动侦听器操作:
protected override async Task RunAsync (CancellationToken cancellationToken)
{
ClientAuthorizationBusCommunicationListener.StartOperations ();
...
这个问题很可能在这里表现出来,因为有问题的总线已经有消息并在创建侦听器的第二个开始触发。尝试访问状态管理器中的任何内容都会引发您所询问的异常。