Azure SDK for .Net:如何为SendMessageAsync设置超时时间
为Azure Service Bus的SendMessageAsync设置超时时间
你可以通过C#的CancellationTokenSource结合SendMessageAsync支持的CancellationToken参数实现超时控制,官方SDK虽未直接提供超时配置项,但利用任务取消机制可满足需求。
异步场景(推荐使用async/await)
这种方式更贴合.NET异步编程规范,避免线程阻塞:
using System.Threading; using System.Threading.Tasks; using Azure.Messaging.ServiceBus; // 创建CancellationTokenSource,指定1秒后自动触发取消 using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(1)); try { await _serviceBusSender.SendMessageAsync(new ServiceBusMessage("Hello"), cancellationTokenSource.Token); } catch (OperationCanceledException) { // 将取消异常转换为明确的超时异常抛出 throw new TimeoutException("消息发送超时,已超过1秒"); }
同步场景(保留Wait()调用的情况)
若需维持同步调用模式,可结合Task.Wait()的超时重载与取消令牌:
using System.Threading; using System.Threading.Tasks; using Azure.Messaging.ServiceBus; using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(1)); Task sendTask = _serviceBusSender.SendMessageAsync(new ServiceBusMessage("Hello"), cancellationTokenSource.Token); try { // 等待任务完成,最长等待1秒 if (!sendTask.Wait(TimeSpan.FromSeconds(1))) { // 超时后主动取消任务 cancellationTokenSource.Cancel(); throw new TimeoutException("消息发送超时,已超过1秒"); } } catch (AggregateException ex) { // 展开AggregateException,处理内部的取消异常 if (ex.InnerException is OperationCanceledException) { throw new TimeoutException("消息发送超时,已超过1秒"); } // 其他异常原样抛出 throw; }
说明
CancellationTokenSource(TimeSpan)会在指定时间后自动触发取消信号,SendMessageAsync检测到信号后会抛出OperationCanceledException- 同步场景中,
Task.Wait(TimeSpan)先等待指定时长,若任务未完成则主动取消并抛出超时异常 - 你可根据业务需求选择直接处理
OperationCanceledException,或转换为更明确的TimeoutException
内容的提问来源于stack exchange,提问作者Gurpreet Kailey
相关产品推荐
相关产品推荐

