取消线程睡眠

时间:2020-02-07 07:54:14

标签: c# multithreading sleep

我有一个具有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);
    }
}

问题是我想在获得另一个键作为输入后立即停止第二个线程。但这不起作用,因为线程仍在休眠并且不响应。

2 个答案:

答案 0 :(得分:1)

只需使用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

答案 1 :(得分:0)

第二个线程在唤醒时应检查布尔值。满足条件时,应将此值设置为false。现在,当第二个线程唤醒时,它将完成其执行。