NanoByte.Common.Tasks.CancellationTokenSource.Cancel C# (CSharp) Method

Cancel() public method

Notifies all listening CancellationTokens that operations should be canceled.
public Cancel ( ) : void
return void
        public void Cancel()
        {
            lock (_lock)
            {
                // Don't trigger more than once
                if (_isCancellationRequested) return;

                _waitHandle.Set();

                _isCancellationRequested = true;
                if (CancellationRequested != null)
                {
                    try
                    {
                        CancellationRequested();
                    }
                    catch (RemotingException)
                    {}
                }
            }
        }

Usage Example

Beispiel #1
0
        public void TestCancel()
        {
            // Prepare a very slow download of the file and monitor for a cancellation exception
            Server.Slow = true;
            var  download                = new DownloadFile(Server.FileUri, _tempFile);
            bool exceptionThrown         = false;
            var  cancellationTokenSource = new CancellationTokenSource();
            var  downloadThread          = new Thread(() =>
            {
                try
                {
                    download.Run(cancellationTokenSource.Token);
                }
                catch (OperationCanceledException)
                {
                    exceptionThrown = true;
                }
            });

            // Start and then cancel the download
            downloadThread.Start();
            Thread.Sleep(100);
            cancellationTokenSource.Cancel();
            downloadThread.Join();

            exceptionThrown.Should().BeTrue(because: "Should throw OperationCanceledException");
        }
All Usage Examples Of NanoByte.Common.Tasks.CancellationTokenSource::Cancel
CancellationTokenSource