我有一个简单的控制台应用程序与2个运行的线程。
第一个线程测量一些值,第二个线程查找用户输入并执行一些鼠标移动。
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);
}
}问题是,一旦我得到另一个键作为输入,我就想停止第二个线程。但是它没有工作,因为线程仍然处于休眠状态,没有反应。
发布于 2020-02-07 16:54:11
只需使用CancellationToken即可完成
传播应该取消操作的通知。
示例
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");
}使用
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();
}结果
Press key to cancel tasks
Waiting
Waiting
Waiting
Waiting
Waiting
Cancelling token
Task Cancelled
Finished
Elvis has left the building发布于 2020-02-07 16:49:54
第二个线程应该在唤醒时检查布尔值。当满足条件时,应将此值设置为false。现在,当第二个线程被唤醒时,它将完成执行。
https://stackoverflow.com/questions/60109210
复制相似问题