C#:非阻塞睡眠

时间:2013-02-18 02:15:31

标签: c# multithreading

我正在为我的Logitech G510 LCD键盘编写一个小应用程序,我遇到了一个小问题。在绘制到我的屏幕后,我希望我的程序变为空闲并保持活动状态,但不会消耗我计算机上的任何资源。

但是,每当引发某个事件时,我都需要打开一个表单。我相信Thread.Sleep()不是最好的方法。

以下是我的代码大致如下:

int main(){
    InitLCD();
    DrawStuff();

    Wait();
}

void HandleEvent(){
    //Create a Form if none exists
}

//Must be called before exiting
void OnExit()
{
    CloseLCD();
}

可能是一个关心事件的独立线程是一个解决方案吗?如果是这样,怎么样?

编辑://应用程序是一个不可见的WinForm应用程序。这意味着,在开始时不会创建任何表单。只有在提出所述事件时,才会创建实际表单。

1 个答案:

答案 0 :(得分:1)

以这种方式尝试逻辑:

public static class Program
    {
        private static AutoResetEvent waithandle = new AutoResetEvent(true);
        static void Main()
        {
            LCDClass lcd = new LCDClass();
            lcd.mid_event += LcdOnMidEvent;
            lcd.exit_event += LcdOnExitEvent;
            lcd.init();


            Thread thread = new Thread(lcd.DrawStuff);
            thread.Start(waithandle);
            waithandle.WaitOne();

        }

        private static void LcdOnExitEvent(object sendet, EventArgs eventArgs)
        {
            //lcd work finished
        }

        private static void LcdOnMidEvent(object sendet, EventArgs eventArgs)
        {
            // handle event, create form
            Application.Run(new MyForm());
        }

    }

    internal class LCDClass
    {
        private AutoResetEvent waithandle;
        internal delegate void MyEventHandler(object sendet, EventArgs e);

        internal event MyEventHandler mid_event;

        protected virtual void OnMidEvent(object sendet)
        {
            MyEventHandler handler = mid_event;
            if (handler != null) handler(sendet, EventArgs.Empty);
        }

        internal event MyEventHandler exit_event;

        protected virtual void OnExitEvent(object sendet)
        {
            MyEventHandler handler = exit_event;
            if (handler != null) handler(sendet, EventArgs.Empty);
        }

        public void init()
        {
        }

        public void DrawStuff(object state)
        {
            // do work here

            // raise event
            mid_event(this, null);

            //do more work

            // raise event
            exit_event(this, null);
            waithandle.Set();

        }

    }