简体   繁体   中英

Detect Nullable change

I am trying to figure out, how I can tell the compiler that my CancellationToken _loadingCts is not null when I call the function ClearCancellationTokenSource

private CancellationTokenSource? _loadingCts = null;
     
private async Task LoadDataAsync()
{
    ClearCancellationTokenSource(_loadingCts, true);
    await foreach (var item in service.GetDataAsync(_loadingCts.Token))
    {

    }
}

private void ClearCancellationTokenSource(CancellationTokenSource? cts, bool createNewTokenSource = false)
{
    cts?.Cancel();
    cts?.Dispose();

    if(createNewTokenSource)
    {
        cts = new CancellationTokenSource();
    }
}

As you can see in my code eaxample above _loadingCts is not null when I call the function before with true because it get's initialized within this method.

When I am trying to access _loadingCts.Token after I called this method with true I am getting a compiler warning CS8602.

Is there any way to fix this? I don't want to do another another nulöl check just to get rid off the warning. The ! is not an option either because the warnings will be displayed again when I am trying to access anything from my CancellationTokenSource again.

using System.Diagnostics.CodeAnalysis;

// ...

private void DisposeCancellationTokenSource(CancellationTokenSource? cts)
{
    cts?.Cancel();
    cts?.Dispose();
}

private void RecreateCancellationTokenSource([NotNull] ref CancellationTokenSource? cts)
{
    ClearCancellationTokenSource(cts);
    cts = new CancellationTokenSource();
}

The [NotNull] attribute tells the compiler that the argument to parameter cts will contain a not-null value after the call. It's not possible to make the NotNull conditional on the value of another bool parameter, so the easiest thing is to split your method into two methods instead of having one method with a bool parameter.

The ref makes it so when you assign a new object to the variable passed to the method, that new object is actually visible to the caller. Otherwise, it's only possible to make caller-visible changes by changing state on the same object. Because only Recreate assigns a new object, it's the only one that needs the ref -- Clear doesn't need it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM