简体   繁体   English

如何在C#中使异步暂停?

[英]How to make async pause in C#?

I have a program written in C# (Visual Studio), that works on a tray. 我有一个用C#(Visual Studio)编写的程序,该程序可以在托盘上工作。 I want it to do one action every 10 minutes. 我希望它每10分钟执行一次操作。 I have following code now: 我现在有以下代码:

while(true)
{
Thread.Sleep(10000);
// my stuff
}

But it doesn't work. 但这是行不通的。 It freezes a program. 它冻结程序。

You should use the timer object and not create a while loop. 您应该使用timer对象,而不要创建while循环。

System.Timers.Timer _timer = new  System.Timers.Timer();
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
//30 seconds
_timer.Interval = 30000;
_timer.Start();

private void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
    //do your logic
}

Thread.Sleep makes the calling thead Sleep for an X ammount of time. Thread.Sleep使调用thead Sleep的时间为X。 If this thread is the frontend thread (the one responsible for handling messages), it will indeed freeze the application since any message for handling events or repainting wont be handeled untill the Thread wakes up again and gets a chance of handling the messages. 如果此线程是前端线程(负责处理消息的线程),则它将冻结应用程序,因为在处理线程或重新绘制消息之前,不会再次处理任何消息,直到线程再次唤醒并有机会处理消息。

What you should do is schedule this logic every 10 seconds. 您应该做的是每10秒安排一次此逻辑。

Drop a timer on your form and specify it to run each 10 seconds. 在表单上放置一个计时器,并指定其每10秒运行一次。 Within the Tick event, call your custom action. 在Tick事件中,调用您的自定义操作。

Thread.Sleep "stops" the current thread. Thread.Sleep“停止”当前线程。 if you only have one thread, everything is paused. 如果只有一个线程,则一切都将暂停。

What do you want to achieve ? 您想实现什么?

Perhaps you need a second thread, or perhaps the better solution a timer which triggers a action every 10 minutes 也许您需要第二个线程,或者更好的解决方案是一个计时器,该计时器每10分钟触发一次操作

s. s。 Task.StartNew() or ThreadPool Task.StartNew()ThreadPool

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM