3 回答

TA貢獻2021條經(jīng)驗 獲得超8個贊
像Ash一樣,我將所有實際的處理代碼編寫在單獨的類庫程序集中,然后由Windows Service可執(zhí)行文件以及控制臺應用程序引用。
但是,有時候了解類庫是否在服務可執(zhí)行文件或控制臺應用程序的上下文中運行很有用。我這樣做的方法是反思托管應用程序的基類。(對VB表示抱歉,但是我認為可以很容易地對C#進行以下修飾):
Public Class ExecutionContext
''' <summary>
''' Gets a value indicating whether the application is a windows service.
''' </summary>
''' <value>
''' <c>true</c> if this instance is service; otherwise, <c>false</c>.
''' </value>
Public Shared ReadOnly Property IsService() As Boolean
Get
' Determining whether or not the host application is a service is
' an expensive operation (it uses reflection), so we cache the
' result of the first call to this method so that we don't have to
' recalculate it every call.
' If we have not already determined whether or not the application
' is running as a service...
If IsNothing(_isService) Then
' Get details of the host assembly.
Dim entryAssembly As Reflection.Assembly = Reflection.Assembly.GetEntryAssembly
' Get the method that was called to enter the host assembly.
Dim entryPoint As System.Reflection.MethodInfo = entryAssembly.EntryPoint
' If the base type of the host assembly inherits from the
' "ServiceBase" class, it must be a windows service. We store
' the result ready for the next caller of this method.
_isService = (entryPoint.ReflectedType.BaseType.FullName = "System.ServiceProcess.ServiceBase")
End If
' Return the cached result.
Return CBool(_isService)
End Get
End Property
Private Shared _isService As Nullable(Of Boolean) = Nothing
#End Region
End Class

TA貢獻1851條經(jīng)驗 獲得超5個贊
什么對我有用:
進行實際服務工作的類在單獨的線程中運行。
此線程從OnStart()方法內(nèi)部啟動,并從OnStop()停止。
服務和控制臺模式之間的決定取決于 Environment.UserInteractive
樣例代碼:
class MyService : ServiceBase
{
private static void Main()
{
if (Environment.UserInteractive)
{
startWorkerThread();
Console.WriteLine ("====== Press ENTER to stop threads ======");
Console.ReadLine();
stopWorkerThread() ;
Console.WriteLine ("====== Press ENTER to quit ======");
Console.ReadLine();
}
else
{
Run (this) ;
}
}
protected override void OnStart(string[] args)
{
startWorkerThread();
}
protected override void OnStop()
{
stopWorkerThread() ;
}
}
- 3 回答
- 0 關注
- 588 瀏覽
添加回答
舉報