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

UWP中调用CancellationTokenSource.Cancel()后IsCancellationRequested更新延迟问题求助

UWP中调用CancellationTokenSource.Cancel()后IsCancellationRequested更新延迟问题求助

我最近碰到个挺奇怪的问题:当调用CancellationTokenSource.Cancel()方法后,IsCancellationRequested属性要过很久才会更新为true。

不确定是不是相关因素,不过我是在和BluetoothLEAdvertisementWatcher配合使用这个取消令牌的,先把这个背景说清楚。

下面是相关的代码片段(完整代码结构太复杂,只摘了关键部分):

首先是AdvertisementHandler类:

internal AdvertisementHandler(ILogger logger)
{
    _logger = logger;

    _adWatcher = new BluetoothLEAdvertisementWatcher();
    _adWatcher.Received += OnAdvertisementReceived;
    _adWatcher.Stopped += OnAdvertisementWatcherStopped;
}

internal void StartWatching(CancellationToken token)
{
    _cancellationToken = token;
    _adWatcher.Start();
}

internal void StopWatching()
{
    _adWatcher.Stop();
}

private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
{
    
    if (_cancellationToken.IsCancellationRequested)
    {
        _logger.LogDebug($"Cancelling device search");

        StopWatching();
        return;
    }

    _logger.LogDebug($"Received an advertisement");

    // 处理广告的逻辑
}

然后是另一个类里的相关代码:

private void DetectNewDevices()
{
    try
    {
        _cancellationSource = new CancellationTokenSource(TimeSpan.FromSeconds(120));

        _logger.LogDebug($"Looking for new {deviceName} devices");

        _adHandler.StartWatching(_cancellationSource.Token);

        Thread.Sleep(250);

    }
    catch (Exception ex)
    {
        _logger.LogException(ex);
    }
}

public bool ChooseDevice(IDeviceInstance deviceInstance)
{
    if (_cancellationSource != null)
    {
        _logger.LogDebug("Choosing A device so cancelling search.");
        _cancellationSource.Cancel();
    }

    // 其他逻辑
}

具体的问题场景是这样的:

  1. 先调用DetectNewDevices(),它会创建一个120秒超时的CancellationTokenSource,把令牌传给_adHandler.StartWatching(),之后蓝牙广告开始正常接收,日志里能不断看到“Received an advertisement”的记录。
  2. 之后调用ChooseDevice()时,我明确执行了_cancellationSource.Cancel(),日志也能看到这条记录,但IsCancellationRequested却迟迟不变成true——有一次甚至等了快2分钟。

重点说明:这不是因为广告事件没触发,期间我收到了很多广告,甚至断点进到OnAdvertisementReceived里查看,IsCancellationRequested还是false,直到很久之后才会变成true。

想请教下有没有人遇到过类似的问题?或者这是不是UWP蓝牙LE框架的某种特性导致的?

备注:内容来源于stack exchange,提问作者komodosp

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 10:33:07