C#延迟线程 [英] C# delaying a thread

查看:91
本文介绍了C#延迟线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个线程:主线程和两个计时器.一段时间后,第一个计时器将激活第二个计时器,然后将其自身禁用.

I have three threads: the main thread and two timers. The first timer activates the second one after a period of time and then disables itself.

我使用"Thread.Sleep(int)"来延迟第二个计时器的激活.但是,当睡眠"功能运行时,整个程序会暂停.

I use "Thread.Sleep(int)" in order to delay the activation of the second timer. But the whole program pauses when the "Sleep" function is working.

如何在不暂停整个程序的情况下暂停线程?

How can I pause a thread without pausing the whole program?

推荐答案

计时器不会在新线程中执行您的代码.在间隔之后,它们在Windows消息队列中引发一个事件,然后该事件由主线程执行,因此 Thread.Sleep(int)会暂停所有操作.

Timers don't execute your code in new threads. After their interval they raise an event in the Windows Message Queue that the main thread then executes, hence why Thread.Sleep(int) is pausing everything.

要解决此问题,您实际上需要启动自己的线程.这是一个简单的过程:

To fix this, you'll need to actually start your own threads. It's an easy process:

        Thread t = new Thread(new ThreadStart(() => {
            // Do Something without parameters
        }));
        t.Start();

        Thread t = new Thread(new ParameterizedThreadStart((obj) => {
            // Do Something with parameters
        }));
        Object obj = ...;
        t.Start(obj);

您可能需要在启动线程之前在线程上设置其他参数,这些参数会影响应用程序的其余部分,例如 IsBackground

There are other parameters you may want to set on a thread before you start it that will affect the rest of your application such as IsBackground

这篇关于C#延迟线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆