我创建了一个表单,里面创建了一个方法,我尝试将其作为不同的线程调用,并且我想暂停 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 运行
最佳答案
这里有几个问题。
- 无需在另一个线程中启动表单,并且可能会产生意想不到的后果
- 您在 UI 线程上,将工作交给另一个线程,然后暂停 UI 线程并阻塞消息泵...hrmm。
- 为什么使用 Thread?与千年同行并使用任务
- 这可能是
async
和await
。不过,我们暂时先把它放在一边
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);
}
});
}
然而,在现代世界中,我们可能会以各种形式之一使用async
和await
模式
示例
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/