Question

Our company provides a network component (DLL) for a GUI application.

It uses a Timer that checks for disconnections. If it wants to reconnect, it calls:

internal void timClock_TimerCallback(object state)
{
  lock (someLock)
  {
    // ...
    try
    {
         DoConnect();
    }
    catch (Exception e)
    {
        // Log e.Message omitted
        // Raise event with e as parameter
        ErrorEvent(this, new ErrorEventArgs(e));
        DoDisconnect();
    }
    // ...
  }
}

So the problem is, inside of the DoConnect() routine a SocketException is thrown (and not caught). I would assume, that the catch (Exception e) should catch ALL exceptions but somehow the SocketException was not caught and shows up to the GUI application.

protected void DoConnect()
{
    //
    client = new TcpClient();
    client.NoDelay = true;
    // In the following call the SocketException is thrown
    client.Connect(endPoint.Address.ToString(), endPoint.Port);
    // ... (login stuff)
}

The doc confirmed that SocketException extends Exception. The stacktrace that showed up is:

TcpClient.Connect() -> DoConnect() -> timClock_TimerCallback

So the exception is not thrown outside the try/catch block.

Any ideas why it doesn't work?

Was it helpful?

Solution

I wrote a little program and was unable to reproduce, a SocketException was caught inside a TimerCallback just fine.

So I suggest you re-think your analysis, the problem may not be what you think it is. A few suggestions:

  • run it outside the Timer. T|hat takes the threading out of the loop.
  • run it in the debugger. Where does the exception really occur?
  • step through the exception handling. Is ErrorEvent doing what it should?

OTHER TIPS

If ErrorEvent really raises another exception (per the comment), then DoDisconnect() is never executed.

Otherwise, the exception you see might be coming form DoDisconnect()

Could you post the DoConnect() code?

Also things to try: Can you catch it in the DoConnect()? Try catching the specific exception instead of just the generic. How does it react if you use debug mode?

Your timClock_TimerCallback isn't called in the same thread as the catch-statement wants to catch an exception. You should catch the exception inside timClock_TimerCallback and then call a method which invokes itself and then rethrow the exception in the right thread.

Not sure this will work, but you could give it a try.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top