Error on Thread.Sleep while using HttpListener

I have code that works fine when independent, just not when together. When a web page is accessed I write to a digital output setting it true for 500ms and then setting it back to false, using Thread.Sleep to get that 500ms pause. I get the error below when I try to execute. If I execute the code through some other trigger such as a digital input it works fine, or if I execute the web page with Thread.Sleep commented otu it works fine. Any good way around this incompatibility?

An unhandled exception of type ‘System.NullReferenceException’ occurred in GHIElectronics.NETMF.W5100.Http.dll

You are using something that is no longer referenced and the GC runs at some point on clears that object you have lost.

The line that throws the error is
Thread.Sleep(500);
How can that be null? The current thread can never be null.

There’s a good chance while you’re stepping in / setting values that you’re not hitting the timing issue that Gus points out - either way there’s a socket or other network object that is being cleaned up by GC that you’re trying to refer to.

If you can post your code it will help you get a solution.

Sleep is not what is throwing hte exception, sleep give the system idle time to cleanup unused resources.

Here is my method that is being called. The first version errors on the Thread.Sleep line based on the debug statements (I see 0 & 1, but not 2) or stepping through, I’ve done both separately because I know somethings fail differently or not at all when you step through. My second method, which also gives my code a 500ms pause always works fine.

    private void LightOn(int Milliseconds = 500)
    {
        Debug.Print("0");
        Light.Write(true);
        Debug.Print("1");
        Thread.Sleep(Milliseconds);
        Debug.Print("2");
        Light.Write(false);
        Debug.Print("3");
    }


    private void LightOn(int Milliseconds = 500)
    {
        Debug.Print("0");
        Light.Write(true);
        Debug.Print("1");
        long end = DateTime.Now.Ticks + Milliseconds * 10000;
        Debug.Print("2");
        while (DateTime.Now.Ticks < end) { }
        Debug.Print("3");
        Light.Write(false);
        Debug.Print("4");
    }

Can you post all of your code? Thread.Sleep() yields the processor over to other threads to execute. Sleep() is almost certainly not the problem. It’s more likely to be something else in another thread that is executing when you call Sleep(). Have you tried stepping through the Sleep() call using F11?

Also, please post your code using the

 tags (1010101 button above).