Can I use cancelationToken == CancellationToken.None to check by default (CancellationToken)

The reason is that if it is CancellationToken.None, I need to add a timeout (so the new CancellationToken from CancellationTokenSource), for example

if (cancellationToken == CancellationToken.None)
{
    var tokenSource = new CancellationTokenSource();
    tokenSource.CancelAfter((int)_timeout.TotalMilliseconds);

    cancellationToken = tokenSource.Token;
}

Another idea is to create a combined token.

Update. Will there be something like this work? Any issues I should know about? Will the GC do what it needs?

public async Task<int> InternalActionAsync(CancellationToken token)
{
    // do something with the token...
    return 1;
}

public Task<int> ExternalActionAsync(CancellationToken token = default(CancellationToken))
{
    var internalTokenSource = 
            new CancellationTokenSource((int)_timeout.TotalMilliseconds);
    var linkedTokenSource = 
            CancellationTokenSource.CreateLinkedTokenSource(token, 
                                                            internalTokenSource.Token);

    return InternalActionAsync(linkedTokenSource.Token);
}
+4
source share
2 answers

First of all, looking at the source code :

public static CancellationToken None
{
    get { return default(CancellationToken); }
}

Thus, you can be sure that they are equal.

CancellationToken, , CancellationToken? , :

public Task<int> ExternalActionAsync(CancellationToken? token = null)
{
    if (token == null)
    {
        var tokenSource = new CancellationTokenSource();
        tokenSource.CancelAfter((int)_timeout.TotalMilliseconds);
        token = tokenSource.Token;
    }

    return InternalActionAsync(token);
}
+2

CancellationToken CancellationToken.None, "". CancellationToken , CancellationToken.None . , , , .

CancellationTokens - , GC - .

, , ( , ). .

0

All Articles