在当前线程中暂停一个Thread

Cer*_*oUC 2 c# c#-4.0

我创建一个表单,内部创建了一个方法,我尝试作为一个不同的线程调用,我想暂停2秒,然后重新开始.但问题是,当我添加thread.sleep.(1000)时,这会冻结我的表单线程而不是另一个线程.

[STAThread]
static void Main()
{
     new Thread(() => Application.Run(new DrawForm())).Start();
}

public partial class DrawForm : Form
{
   private void CallToRun(object sender, EventArgs e)
   {
      if (menu.option == 1)
      {
          while (true)
          {
             Thread t1 = new Thread(() => MyMethod());
             t1.Start();
             Thread.Sleep(2000)//but this stop my current thread and not my MyMethod()
         }
      }
   }

  private void MyMethod()
  {
      Console.WriteLine("Runing....")
  }
}
Run Code Online (Sandbox Code Playgroud)

应该是这样的事情:跑1 ... 2 ..跑1 2跑

AAA*_*ddd 5

这里有几个问题.

  1. 没有必要在另一个线程中启动您的表单,并可能有意想不到的后果
  2. 你在UI线程上,你将你的工作交给另一个线程,你正在暂停UI线程线程并阻止消息泵... hrmm.
  3. 你为什么使用Thread?获得千禧年并使用任务
  4. 这可能是asyncawait.但是,让我们把它放在一边

Program.cs中

// lets start normally 
[STAThread]
static void Main()
{
   Application.EnableVisualStyles();
   Application.SetCompatibleTextRenderingDefault(false);
   Application.Run(new DrawForm ());
}
Run Code Online (Sandbox Code Playgroud)

这是最容易做到的

Thread t1 = new Thread(() => 
{
    MyMethod();
    Thread.Sleep(2000); //pausing the right thread
);
Run Code Online (Sandbox Code Playgroud)

但是你可以做到这一点

private void CallToRun(object sender, EventArgs e)
{
   // runs concurrently
   Task.Run(
      () =>
         {
            while (true) // woah are you sure you want to run this forever?
            {
               MyMethod();

               //doesn't pause the message pump
               Thread.Sleep(2000);
            }
         });

}
Run Code Online (Sandbox Code Playgroud)

然而,在现代世界中,我们可能会以各种形式使用asyncawait模式化

private async Task CallToRun(object sender, EventArgs e)
{
   while (true) // woah this stil smells
   {
      MyMethod();
      await Task.Delay(2000); // not pausing the message pump, yay
   }
}
Run Code Online (Sandbox Code Playgroud)