How to determine if a previous instance of my application is running?

后端 未结 10 1512
梦谈多话
梦谈多话 2020-12-05 10:31

I have a console application in C# in which I run various arcane automation tasks. I am well aware that this should really be a Windows Service since it nee

10条回答
  •  再見小時候
    2020-12-05 10:59

    This article talks about it: Prevent a second process instance from running. It's in VB.net but you can convert it.

    The problem in writing a generic function that checks whether the current application is already running comes from the fact that the ProcessName property of the Process object seems to be limited to 15 characters, so longer process names are truncated.
    A safer way to retrieve a process name is to get the filename of its main module and dropping the extension. The following reusable routine uses this approach:
    
    Function AppIsAlreadyRunning() As Boolean
        ' get the filename of the main module
        Dim moduleName As String = Process.GetCurrentProcess.MainModule.ModuleName
    
        ' discard the extension to get the process name
        Dim procName As String = System.IO.Path.GetFileNameWithoutExtension(moduleName)
    
        ' return true if there are 2 or more processes with that name
        If Process.GetProcessesByName(procName).Length > 1 Then
            Return True
        End If
    End Function
    

提交回复
热议问题