使控制台应用程序的行为类似于Windows应用程序 [英] Making a console application behave like a Windows application
问题描述
我有一个控制台应用程序,我希望它能够等待直到引发某些事件.但是它执行代码并退出:
I have a console application, and I want it to wait till some event is raised. But it executes the code and exits:
static void Main(string[] args)
{
var someObjectInstance = new SomeObject();
someObjectInstance.SomeEvent += SomeEventHandler;
}
static void SomeEventHandler()
{
//Some logic
}
我想让我的应用程序像Windows应用程序一样运行
I want to make my application behave like a Windows application where
Application.Run(new Form1());
被调用并运行消息循环.
is called and the message loop is run.
但是我既不需要消息循环也不需要任何形式.所以看起来像是开销.有没有更轻巧的方法可以实现我的目标?
But I don't need neither a message loop nor any form. So it looks like overhead. Is there a more light-weight way to achieve my goal?
推荐答案
首先,除非 SomeObject
打算在单独的线程上引发事件,否则,如果不进行某种形式的处理,这将无法正常工作在 SomeObject
中.但是,如果采用这种方式设计,那将非常简单.
First off, unless SomeObject
is going to raise the event on a separate thread, this won't work without some form of processing in SomeObject
. If it's designed that way, however, this is fairly straightforward.
一种非常有效的处理方法是等待WaitHandle:
A very efficient way of handling this is to just wait on a WaitHandle:
private static ManualResetEvent waitHandle = new ManualResetEvent(false);
static void Main(string[] args)
{
var someObjectInstance = new SomeObject();
someObjectInstance.SomeEvent += SomeEventHandler;
waitHandle.WaitOne(); // Will block until event occurs
}
static void SomeEventHandler()
{
//some logic
waitHandle.Set(); // Will allow Main() to continue, exiting the program
}
这篇关于使控制台应用程序的行为类似于Windows应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!