如何捕获第三方库中未等待的任务抛出的异常?

时间:2017-10-02 15:03:36

标签: c# exception async-await task topshelf

我有一个依赖第三方库EasyRedisMQ的Windows服务(使用Topshelf)。不幸的是,我刚刚在其中一个库方法中发现了以下代码:

    public async Task InitializeAsync()
    {
        if (SubscriberInfo == null) throw new NullReferenceException("SubscriberInfo is required.");
        if (string.IsNullOrWhiteSpace(SubscriberInfo.SubscriberId)) throw new NullReferenceException("SubscriberId is required");
        if (string.IsNullOrWhiteSpace(SubscriberInfo.ExchangeName)) throw new NullReferenceException("ExchangeName is required");
        if (string.IsNullOrWhiteSpace(SubscriberInfo.QueueName)) throw new NullReferenceException("QueueName is required");
        if (OnMessageAsync == null) throw new NullReferenceException("OnMessageAsync is required");

        await _cacheClient.SubscribeAsync<string>(SubscriberInfo.ExchangeName, DoWorkAsync);

        DoWorkAsync("").FireAndForget();
    }

这里DoWorkAsync返回一个任务,但是正如FireAndForget所指出的那样,遗憾的是没有等待。实际上,FireAndForget是一个空体的方法(唯一的目的是明确表示不等待任务)。 查看完整的源代码here

问题是DoWorkAsync偶尔会抛出异常,导致服务崩溃:

{
  "Depth": 0,
  "ClassName": "StackExchange.Redis.RedisConnectionException",
  "Message": "SocketFailure on RPOP",
  "Source": "mscorlib",
  "StackTraceString": "   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at StackExchange.Redis.Extensions.Core.StackExchangeRedisCacheClient.<ListGetFromRightAsync>d__67`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at EasyRedisMQ.Models.Subscriber`1.<GetNextMessageAsync>d__12.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at EasyRedisMQ.Models.Subscriber`1.<DoWorkAsync>d__13.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at StackExchange.Redis.Extensions.Core.StackExchangeRedisCacheClient.<>c__DisplayClass59_0`1.<<SubscribeAsync>b__0>d.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__6_1(Object state)\r\n   at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)\r\n   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)\r\n   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)\r\n   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()\r\n   at System.Threading.ThreadPoolWorkQueue.Dispatch()\r\n   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()",
...
}

我非常想捕获异常(因为它实际上是无害的并且只是重试操作)。但是,在阅读this StackOverflow question并尝试使用AppDomain.CurrentDomain.FirstChanceException之后,我没有太大的希望。 FirstChanceException的问题在于它出现在Tophelf的

之外
HostFactory.Run(hostConfigurator => { ... }

方法,其中我引用了服务(业务逻辑所在的位置):

hostConfigurator.Service<IConsumer>(serviceConfigurator =>
{
    serviceConfigurator.ConstructUsing(() => IocContainer.IocContainer.Instance.Resolve<IConsumer>());
    serviceConfigurator.WhenStarted(consumer => { /* Here I have control */ });
    ...
}

有没有人知道如何处理这种情况?

1 个答案:

答案 0 :(得分:1)

订阅TaskScheduler的event

TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
//...

private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
    e.SetObserved();
}