Reputation: 43
I have a simple Console application with 2 running threads.
The first thread is measuring some values, and the second thread looks for user input and performs some mouse movements.
while (true)
{
if (Input.IsKeyDown(VC_L))
{
Mouse.Move(300, 500);
Thread.Sleep(thread1_delay);
Mouse.Move(670, 300);
Thread.Sleep(thread1_delay);
Mouse.Move(870, 700);
Thread.Sleep(thread1_delay);
}
}
The problem is I want to stop the second thread as soon as I get another key as input. But it's not working since the thread is still sleeping and doesn't react.
Upvotes: 2
Views: 2768
Reputation: 81573
Just use a CancellationToken
and be done with it
Propagates notification that operations should be canceled.
Example
public static async Task DoFunkyStuff(CancellationToken token)
{
// a logical escape for the loop
while (!token.IsCancellationRequested)
{
try
{
Console.WriteLine("Waiting");
await Task.Delay(1000, token);
}
catch (OperationCanceledException e)
{
Console.WriteLine("Task Cancelled");
}
}
Console.WriteLine("Finished");
}
Usage
static async Task Main(string[] args)
{
var ts = new CancellationTokenSource();
Console.WriteLine("Press key to cancel tasks");
var task = DoFunkyStuff(ts.Token);
// user input
Console.ReadKey();
Console.WriteLine("Cancelling token");
// this is how to cancel
ts.Cancel();
// just to prove the task has been cancelled
await task;
// because i can
Console.WriteLine("Elvis has left the building");
Console.ReadKey();
}
Results
Press key to cancel tasks
Waiting
Waiting
Waiting
Waiting
Waiting
Cancelling token
Task Cancelled
Finished
Elvis has left the building
Upvotes: 4
Reputation: 23419
The second thread should check for a Boolean value when it wakes up. You should set this value to false when your condition is met. Now when the second thread wakes up it will complete it's execution.
Upvotes: 0