You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 08:32:25