我创建一个表单,内部创建了一个方法,我尝试作为一个不同的线程调用,我想暂停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跑
这里有几个问题.
async和await.但是,让我们把它放在一边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)
然而,在现代世界中,我们可能会以各种形式使用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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53 次 |
| 最近记录: |