Forked from tqk2811/CancellationTokenSourceExample.cs
Created
April 26, 2023 13:14
-
-
Save lovmoon3k/ccf7914ccb69d3adf27d668e888ef774 to your computer and use it in GitHub Desktop.
Ví dụ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CancellationTokenSource source = null; | |
void Run() | |
{ | |
if(source?.IsCancellationRequested != false)//true hoặc source null | |
{ | |
source?.Dispose(); | |
source = new CancellationTokenSource(); | |
} | |
Task.Run(() => | |
{ | |
try | |
{ | |
using CancellationTokenSource source2 = new CancellationTokenSource(); | |
using var reg = source.Token.Register(() => source2.Cancel());//xài Register khi cần trigger source2 | |
while (!source2.IsCancellationRequested)//không exception | |
{ | |
source2.Token.ThrowIfCancellationRequested();//throw exception | |
Task.Delay(1000, source2.Token).Wait();//throw exception | |
using Stream stream1 = new MemoryStream(); | |
using Stream stream2 = new MemoryStream(); | |
stream1.CopyToAsync(stream2, source2.Token).Wait();//throw exception | |
} | |
Process process = null; | |
using var reg2 = source.Token.Register(() => process.Kill());//xài Register khi cần kill process; | |
process.WaitForExit(); | |
} | |
catch(OperationCanceledException oce) | |
{ | |
Console.WriteLine("Bị cancel"); | |
} | |
}); | |
} | |
void Cancel() | |
{ | |
source?.Cancel(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment