Search code examples
c#tasktokencancellationcancellationtokensource

CancellationTokenSource proper replace with new one


The Window hides automatically after 5 seconds after it appears (ShowWindow method). It can be also hide manually (HideWindow method). Here is my current implementation.

The issue: When I open and then close window manually some times in row, it then hides immediately to 1 sec after opening. It shouldn't by design. The reason is I replace CTS with new one, and cancellation is never requested. I have poor skill with CTS and can't get in mind how to implement this properly.

public class Window
    {
        public bool Visible { get; set; }
        public CancellationTokenSource HideErrorWindowCTS { get; set; }

        public async void ShowWindow()
        {
            Visible = true;
            await Task.Delay(TimeSpan.FromSeconds(5));
            if (!HideErrorWindowCTS.IsCancellationRequested)
            {
                Visible = false;
            }
        }

        public void HideWindow()
        {
            HideErrorWindowCTS.Cancel();
            HideErrorWindowCTS = new CancellationTokenSource();
            Visible = false;
        }
    }

Solution

  • Because ShowWindow looks at HideErrorWindowCTS, it's looking at the newly updated cancellation token source, not the token corresponding to the CTS at the time you showed the window. Just grab ahold of that token and store it in a local variable before you wait, so that even if HideErrorWindowCTS changes, you still have the same token to check after the delay has finished.