CancellationTokenSource cts = new CancellationTokenSource(); Task th = new Task(OutHookProc.prockill, cts.Token); I stop like this:
cts.Cancel(); How to stop?
You cannot stop a running task in the same way that you cannot stop a running thread. You can only ask the task to stop, and hope that he will listen to your request.
If the OutHookProc.prockill method OutHookProc.prockill under your control, change its signature so that it also CancellationToken , pass the token also there and in the method from time to time check the token and stop working if the token requests it. If you call other asynchronous methods inside OutHookProc.prockill , pass them a token too.
If the method is not under your control and does not provide means for stopping, you can’t stop it at all. The only thing that can be done is to ignore the result of the task execution, but at the same time it will continue to run in the background.
public static void prockill(){ while(true) ... // тут просто килл поцессов } , what should I do better? - GooliveRtrue check the flag that you do not need to go out - Grundywhile (!token.IsCancellationRequested) ... - VladDI tried to do as described here.
private static bool Round = true; static CancellationTokenSource cts; public static void Start() { cts = new CancellationTokenSource(); var task = Task.Run(() => prockill(cts.Token), cts.Token); } public static void prockill(CancellationToken cancellationToken) { while (Round) { try { foreach (string str in strArray) { Process[] processesByName = Process.GetProcessesByName(str); foreach (Process process in processesByName) process.Kill(); } Thread.Sleep(1000); cancellationToken.ThrowIfCancellationRequested(); } catch (Exception) { Round = false; } } } public static void Cancel() { cts.Cancel(); } I want your criticism, kicks) I want to understand the logic and what should not be done ?!
[Edit] Changed the code a bit:
static CancellationTokenSource cts = new CancellationTokenSource(); public static void Start() { var task = Task.Run(() => prockill(cts.Token)); } public static async Task prockill(CancellationToken cancellationToken) { try { while (!cancellationToken.IsCancellationRequested) { await Task.Delay(500, cancellationToken); foreach (string str in strArray) { Process[] processesByName = Process.GetProcessesByName(str); foreach (Process process in processesByName) process.Kill(); } } } catch (OperationCanceledException) { } catch (Exception) { // другая ошибка } } public static void Cancel() { cts.Cancel(); } It seems everything works ultra fast, nothing buggy. Looking for improvement tips, what can I add / change ?!
Round can be removed. And checking the cancellationToken.IsCancellationRequested needs to be done inside the foreach . - Alexander Petrovstatic void prockill use async Task ? - GooliveRSource: https://ru.stackoverflow.com/questions/651951/
All Articles