Last active
April 26, 2023 13:14
-
-
Save tqk2811/da638dfba8d7ba27ff874b18fad90a33 to your computer and use it in GitHub Desktop.
Ví dụ
This file contains 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