attempted to read/write protected memory... THREADING probably

i have a .net 2, visual basic app im developing, and im trying to make it single instance via the apps config menu. i also placed a msgbox in the StartNextInstance event of the application just to see if it gets there.
the thing is, it shows me the form, and after a second or 2, i get an accessviolationerror, "attempted to read/write protected memory...".
i used to get this a while ago when i was programming internet access for my app, if i had Eset's NOD32 antivirus engine active i got that message, otherwise i didnt.
so i feel it has something to do with the threading or something like that. maybe its trying to access something that its already accesed by another process? did anybody face this problem before? how do i go about debugging and solving this? i really need this app to be single instance, and in the event of a second instance, pass the command line args to the first instance and then kill the second instance.
please help?
LVL 13
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mike TomlinsonMiddle School Assistant TeacherCommented:
Go to your Project Properties and check the "Make single instance application" checkbox.
Now click on the "View Application Events" button in the bottom right and paste the code below.

The code that takes the command line arguments for a "next instance" and places it in the Form1 titlebar:

Namespace My

    ' The following events are availble for MyApplication:
    ' Startup: Raised when the application starts, before the startup form is created.
    ' Shutdown: Raised after all application forms are closed.  This event is not raised if the application terminates abnormally.
    ' UnhandledException: Raised if the application encounters an unhandled exception.
    ' StartupNextInstance: Raised when launching a single-instance application and the application is already active.
    ' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
    Partial Friend Class MyApplication

        Private Sub MyApplication_StartupNextInstance(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
            Dim args As String = ""
            Dim arg As String
            For Each arg In e.CommandLine
                args &= " " & arg
            Form1.Text = args
        End Sub

    End Class

End Namespace

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
newyuppieAuthor Commented:
hi Idle_Mind
thanks for responding so fast

ive been debugging line by line, and exactly on this argument

For Each arg In e.CommandLine

i get this error:
System.AccessViolationException was unhandled
  Message="Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
       at System.Net.UnsafeNclNativeMethods.OSSOCK.WSAGetOverlappedResult(SafeCloseSocket socketHandle, IntPtr overlapped, UInt32& bytesTransferred, Boolean wait, IntPtr ignored)
       at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
       at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)

what could be wrong?
thank you
I don't know if I am I understand the question well but if you want to ensure only one instance of your app is running then here is a couple of ways to do it
Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

Mike TomlinsonMiddle School Assistant TeacherCommented:
Try creating a New, blank project with just the instancing code and see if it still crashes...
newyuppieAuthor Commented:
idlemind, i have the same issue...
Mike TomlinsonMiddle School Assistant TeacherCommented:
I have no idea then...

Do you have all the latest updates/service packs for your system?
newyuppieAuthor Commented:
have win xp pro sp2
.net framework 2.0.50727
visual basic 2005 8.0.50727.42 (RTM.50727-4200)

.. i really dont understand this. one more thing is very odd, when i debug step by step (F8) i get the error on that line
For Each arg In e.CommandLine

i have tested using the immediate window, i did "?e.commandline" when the cursor was stopped just before running that line, and i get the print of the commandline with no error, everything ok. but if i run that line i get the error......
Mike TomlinsonMiddle School Assistant TeacherCommented:
You could try reinstalling VB...   =\
newyuppieAuthor Commented:
i did last night, i guess ill have to format disk? if you think of soemthing else please let me know ?

to qbzu, thanks for the link. ill check it out, it's my second option (using mutex), altough its in C, and im using visual basic. do you have a link like that to a VB code?
This VB code is similar

Imports System.Threading

    Private siMutex As Mutex
    Public Sub main()
        siMutex = New Mutex(False, "aUniqueName")
        If (Not siMutex.WaitOne(0, False)) Then
            MessageBox.Show("Application is Running")
            MessageBox.Show("Application Not Running")
        End If
    End Sub

You can replace aUniqueName with Assembly.GetExecutingAssembly().FullName
Mike TomlinsonMiddle School Assistant TeacherCommented:
Right gbzhhu...there are many different ways to figure out if an application is already running.

The tricky part is getting the command line parameters for the new instance, passed back to the already running instance.  Something which your code does not address at all.

The .Net 2.0 Application Model is ~SUPPOSED~ to handle this gracefully:

It does in fact work, and I have personally written code before that does just that.

We just need to figure out why newyuppies computer is crashing...  =)

I don't know much about .NET 2.0 (just reading a book on it).  Thanks for the link, I'll have a read.  Though I am not the asker I am here to learn from others and contribute when I can

Does newyuppies code work on another PC?  I'd suggest doing that first
newyuppieAuthor Commented:
thanks for the contribution gbzhhu. idle_mind is right, what i need is to pass the arguments over to the first instantiated app. i've been reading some codes and am trying to adapt the mutex/hwnd duo instead of visual basic 2005 native "make single instance".
please if you have any more ideas let me know.

ps. it does work on another computer (the runtimes), but i dont have the developing program on the other comp so its a pain to install my app on the other comp every time i want to test it.

thanks for all the contributions, ill keep this open for a while to see, otherwise both will get the points for helping me. thanks
newyuppieAuthor Commented:
I will close this question and give IdleMind and gbzhhu the points (proportionally) for participating and trying to help. I think its a problem with my installation of Visual Studio so i should format C and reinstall to really see if that helps. anyway, thats not gonna happen anytime soon (its a pain in the ars#e).

i ended up using a mutex to check for single instance, and found a code somewhere to use hWnd messages to pass information to the owner app.

ps. idlemind, you mentioned that you have written code that performs this, maybe you could send me an example of how you did it, that would be very helpful to me as i dont particularly like the hWnd method, it makes all my debugging a pain because everytime i keep debugging the hWnd messages for hours...
Mike TomlinsonMiddle School Assistant TeacherCommented:
The example is posted at the top (it passes the command line args for multiple instances to the first instance)...

I was just stating that I have personally tested the code and had it work "as advertised" by Microsoft.

Here is an app that uses the new application model to make a tray icon pop up:
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.