代码之家  ›  专栏  ›  技术社区  ›  Vaccano

非终止/非阻止Windows Mobile应用

  •  0
  • Vaccano  · 技术社区  · 15 年前

    我有一个控制台应用程序,我想继续运行在后台。我想,如果我启动它,然后告诉它等待,事情会成功的。但等我拿到它,它会冻结应用程序。

    这是我的代码:

    班级计划 { 静态公共ManualResetEvent StopMain;

        static void Main(string[] args)
        {
            // Hide the cursor.
            Cursor.Current = Cursors.Default;
    
            StopMain = new ManualResetEvent(false);
    
            RunHook runHook = new RunHook();
    
            // wait until signalled by Program.StopMain.Set();
            StopMain.WaitOne();             
    
        }
    }
    
    class RunHook
    {
        private HookKeys hook;
        public RunHook()
        {
            hook = new HookKeys();
            hook.HookEvent += EventForHook;
        }
    
        private void EventForHook(HookEventArgs e, KeyBoardInfo keyBoardInfo, 
          ref Boolean handled)
        {
            if ((keyBoardInfo.scanCode == 4) && (keyBoardInfo.vkCode == 114))
                handled = true;
        }
    }
    

    有什么想法可以让这场比赛在后台进行,但永远不会结束?

    1 回复  |  直到 15 年前
        1
  •  2
  •   ctacke    15 年前

    你看到的行为是预期的。你只有一个线程,它处于等待状态。要获得某种形式的活动,您必须让调度器实际执行一些操作。后台线程是实现此目的的一种方法:

    static void Main(string[] args)    
    {
        StopMain = new ManualResetEvent(false);
        bool exit = false;
    
        new Thread(
            delegate 
            { 
                new RunHook(); 
                while(!exit) { Thread.Sleep(1); }                 
            }
        ).Start();
    
        StopMain.WaitOne();
        exit = true;
    }
    

    另一种方法是让主线程屈服:

    static void Main(string[] args)    
    {
        StopMain = new ManualResetEvent(false);
    
        RunHook runHook = new RunHook(); 
    
        while(!StopMain.WaitOne())
        {
            Thread.Sleep(1);
        }
    }
    

    当然也有其他办法。就我个人而言,这两件事我都不会做。相反,我将向RunHook类添加一个阻塞方法,并在完成或发出信号时让它返回。