简体   繁体   中英

Exception being thrown multiple times

Basically I am ting to catch any exception off a block of code, and fire said code one.

try {
     CODE
catch (Exception e) 
{
     DO THIS ONCE
} 
finally 
{
     CODE
}

In Depth

So I have been creating a TCP/SOCKET Server. Which can work with multiple clients. And send/recite (I/O) Data. It works well, and has been for a long time now. But I have found in my console that it says this:

MyConsole

This is bad because if it thinks the user disconnected twice it can create many problems. The way I know if a user has disconnected is by sending data to them every 200ms. And if there is a error then print they disconnected remove them from the client list, and disconnect there stream/tcp.

 static bool currentlyUsing;
    private static void PingClient(Object o)
    {
        if (!currentlyUsing)
        {
            if (clientsConnected.Count != 0)
            {
                foreach (Client c in clientsConnected)
                {
                    try
                    {
                        c.tcp.Client.Blocking = false;

                        c.tcp.Client.Send(new byte[1], 0, 0);
                    }
                    catch (Exception e)
                    {
                        currentlyUsing = true;
                        Console.WriteLine("[INFO] Client Dissconnected: IP:" + c.ip + " PORT:" + c.port.ToString() + " Reason:" + e.Message);
                        clientsConnected.Remove(c);
                        c.tcp.Close();
                        break;
                    }
                    finally
                    {
                        currentlyUsing = false;
                    }
                    GC.Collect();
                }
            }
        }

Is there a way to make it so it catches it only once, or catches it multiple times but only fires the code I want once?

If I understand your question correctly: you want to try to run the code on each iteration of the foreach block, and always run the finally code for each iteration, but only run the catch code once?

If so:

Before the foreach block, define:

bool caught = false;

And then after:

catch (Exception e)
{
    if (caught == false)
    {
        caught = true;
        ...
    }
}

I was making multiple timers. So it overlapped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM