很容易让WCF服务在控制台应用程序中运行。我无法获得自行托管的WCF在Windows服务中工作。可能太多的安全问题需要处理。为了改进控制台应用程序服务托管示例,我制作了一个AttachService方法,它可以像这样在自己的线程上运行。
public static AutoResetEvent manualReset;
// Host the service within this EXE console application.
public static void Main()
{
manualReset = new AutoResetEvent(false);
ThreadPool.QueueUserWorkItem(AttachService);
//put Set() signal in your logic to stop the service when needed
//Example:
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
} while (key.Key != ConsoleKey.Enter);
manualReset.Set();
}
static void AttachService(Object stateInfo)
{
// Create a ServiceHost for the CalculatorService type.
using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), new Uri("net.tcp://localhost:9000/servicemodelsamples/service")))
{
// Open the ServiceHost to create listeners and start listening for messages.
serviceHost.Open();
// The service can now be accessed.
//Prevent thread from exiting
manualReset.WaitOne(); //wait for a signal to exit
//manualReset.Set();
}
}
我的目标是使用OnStart方法中使用Process类的Windows服务执行此控制台应用程序。感谢@Reed Copsey对WaitOne()的建议。
值得注意的是,Thread.Sleep(0)只能休眠足够长的时间,让其他线程运行,然后返回。它不会有等待任何一段时间的效果。您可能已经注册了Thread.Sleep(Timeout.Infinite)(值为-1),该值将无限期阻止,但ManualResetEvent比此更好。 – Josh 2011-01-12 02:18:50
相关提示谢谢您的帮助! – bunglestink 2011-01-12 02:23:23