Delegate 和 CancellationToken 故障排除

delegate and cancellationtoken troubleshooting

提问人:Alexey Alferov 提问时间:6/20/2023 最后编辑:Alexey Alferov 更新时间:6/20/2023 访问量:33

问:

我不明白为什么我得到System.NullReferenceException:对象引用未设置为对象的实例。 我想将委托 ConnectAsyncDelegate 传递给 Commit 函数。 有必要使用 CancellationToken,所以我有委托,它获取 CancellationToken,然后我将其传递给 Commit。 在 Commit 函数中创建了 cts。令牌,并传递给 method(cts.令牌)。 在这一部分中,我收到错误return await method(cts.Token);

Func<CancellationToken, Task<int?>> ConnectAsyncDelegate = async cts => await tunnel.sslStreamServer.ReadAsync(buffer, cts);

int? response = await Tunneling.Commit(method: ConnectAsyncDelegate);

public static async Task<int?> Commit(Func<CancellationToken, Task<int?>>? method = null, Action<CancellationToken>? action = null, CancellationToken cancellationToken = default)
    {
        using (var timeout = new CancellationTokenSource(Settings.IoTimeout))
        {
            var cts = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, cancellationToken);
            try
            {
                cts.Token.ThrowIfCancellationRequested();
                action?.Invoke(cts.Token);
                if (method != null)
                {
                    return await method(cts.Token);
                }
                return -1;
            }
            catch (OperationCanceledException oex)
            {
                if (timeout.Token.IsCancellationRequested)
                {
                    throw new OperationCanceledException("Timed out waiting the operation.", oex, timeout.Token);
                }
                throw;
            }
        }
    }

我已经检查了 cts。令牌和方法不为空,但仍然不起作用

委托 nullreferenceexception 匿名函数 取消令牌

评论


答:

0赞 Alexey Alferov 6/20/2023 #1

好吧,我只是错过了这件事tunnel.sslStreamServer.ReadAsync(buffer, cts);tunnel.sslStreamClient.ReadAsync(buffer, cts);