• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 490
  • Last Modified:

Creating a text lock file...

I do not want two instances of my program running at the same time..
If a second instance of the program is then run...:
1) If there is no lock file already (then it is really the first instance) it will create it and carrying out some processing.
2) However if a instance of the lock file already exists the second instance of the program will try to delete it as the first instance of the program holds an exclusive lock the second instance will raise an error which i'll handle in my code. (the second instance of the program not run and end gracefully).
How do I do this..?  or is there a better way...?

0
ISC
Asked:
ISC
  • 3
  • 3
  • 2
1 Solution
 
vigylantCommented:
Use this code to check if theres more than one instance running...
        For Each prc As Process In Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName)
            If prc.Id = Process.GetCurrentProcess.Id Then Continue For
            If prc.MainModule.FileName = Process.GetCurrentProcess.MainModule.FileName Then
 
                Process.GetCurrentProcess.Kill()
 
            End If
        Next

Open in new window

0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
You indicated that you are using VB.Net 2005...

...the ability to prevent multiple instances is BUILT-IN via the Application Model:
http://msdn.microsoft.com/en-us/library/w3xx6ewx.aspx

In Project --> Properties, check the "Make Single Instance Application" box.

The StartupNextInstance() event will fire whenever another instance is "spawned":
http://msdn.microsoft.com/en-us/library/b9z4eyh8.aspx
0
 
vigylantCommented:
I didnt know, thanks :D
However, it seems the communication that is being used is TCP/IP, which is completely silly if you ask me... Why didnt microsoft use pipes instead?
0
Learn to develop an Android App

Want to increase your earning potential in 2018? Pad your resume with app building experience. Learn how with this hands-on course.

 
ISCAuthor Commented:
Idle_Mind:

Thanks, my project is a Console project and the 'Make Single Instance' application is greyed out... I am not sure whether this is becuase this is a console project or not...

Rgds Ian
0
 
vigylantCommented:
Yea, thats why, you need to enable the applicaton framework, and you cant do that with a console application.
Here is some sample code which should work with a console app:
Modify it to suit your needs.
Shared Sub PipeConnect() is the sub that is called when a new instance detects an instance is already running.
Namespace Internal
    Friend Class PipeSystem
 
        Private Const PipeName As String = "XFNewsNZBPipe"
        Private WithEvents PipeWorker As New BackgroundWorker
        Public Event OnIncomingFile(ByVal Filename As String)
 
        Friend Sub New()
 
            PipeWorker.WorkerReportsProgress = True
            PipeWorker.RunWorkerAsync()
 
        End Sub
        Shared Sub PipeConnect()
 
            Dim PipeClient As New Pipes.NamedPipeClientStream(".", PipeName, Pipes.PipeDirection.Out, Pipes.PipeOptions.None)
            PipeClient.Connect(3000)
 
            Dim SW As New StreamWriter(PipeClient)
            SW.AutoFlush = True
 
            For Each FN As String In My.Application.CommandLineArgs
                If File.Exists(FN) Then SW.WriteLine(FN)
            Next
 
            SW.WriteLine(".")
            SW.Close()
 
        End Sub
 
        <DebuggerHidden()> _
        Private Sub PipeWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles PipeWorker.DoWork
 
            Dim PipeServer As New Pipes.NamedPipeServerStream(PipeName, Pipes.PipeDirection.In)
            Dim SR As New StreamReader(PipeServer)
            Dim STR As String = Nothing
 
            Do
 
                PipeServer.WaitForConnection()
 
                STR = SR.ReadLine()
                While Not STR = "."
                    Try
                        PipeWorker.ReportProgress(0, STR)
                    Catch : End Try
                    STR = SR.ReadLine()
                End While
 
                PipeServer.Disconnect()
 
            Loop
 
        End Sub
        Private Sub PipeWorker_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles PipeWorker.ProgressChanged
 
            If File.Exists(e.UserState) Then RaiseEvent OnIncomingFile(e.UserState)
 
        End Sub
 
    End Class
End Namespace

Open in new window

0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Does it really need to be a console app?  You can use a Forms project and make the form invisible by setting the Opactiy() Property to 0 (zero).
0
 
ISCAuthor Commented:
Does it really need to be a console app?  - Yes it does.....
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Okey dokey...then you'll need to use one of the methods proposed by vigylant...

...or handle the original error in a different way:

    "the second instance of the program will try to delete it as the first instance of the program holds an exclusive lock the second instance will raise an error which i'll handle in my code. (the second instance of the program not run and end gracefully)."

We could look into that code if you want.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 3
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now