We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

Creating a text lock file...

ISC
ISC asked
on
Medium Priority
500 Views
Last Modified: 2013-11-05
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...?

Comment
Watch Question

Commented:
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

Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
CERTIFIED EXPERT
Top Expert 2009

Commented:
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

Commented:
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?
ISC

Author

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
Commented:
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

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
CERTIFIED EXPERT
Top Expert 2009

Commented:
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).
ISC

Author

Commented:
Does it really need to be a console app?  - Yes it does.....
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
CERTIFIED EXPERT
Top Expert 2009

Commented:
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.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.