c# - 暂停当前​​线程内的线程

标签 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....")
  }
}

应该是这样的: 运行 1.. 2.. 运行 1 2 运行

最佳答案

这里有几个问题。

  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 ());
}

最简单的做法是

Thread t1 = new Thread(() => 
{
    MyMethod();
    Thread.Sleep(2000); //pausing the right thread
);

但是你可以这样做

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);
            }
         });

}

然而,在现代世界中,我们可能会以各种形式之一使用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
   }
}

关于c# - 暂停当前​​线程内的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54156040/

相关文章:

c# - Dapper 和 SQL Server 数据库入门

c#-4.0 - 启用 Topshelf 的 Windows 服务将无法调试

c#-4.0 - 如何通过WMI和C#查询远程计算机中的文件夹大小

c# - 使用带有 connection.open 的语句

c# - 并发堆栈 : How to check if contains object?

c# - 如何在 Entity Framework 中使用分部类的非数据库属性进行关联

C# - Websocket - 将消息发送回客户端

c# - 在单个 View 中对 RadioButton 进行分组,并正确回传表单数据

excel - 在 Selenium C# 中使用 Excel 数据读取器时,似乎没有选项可以将我的第一行设置为列名称

c# - 序列化 HashSet