views:

98

answers:

3

okay, so here is what im doing:

class Connection
{
    public int SERVERID;
    private Thread connection;
    public Connection()
    {
        connection = new Thread(new ThreadStart(this.Run));
    }
    public void Start(int serverid)
    {
        SERVERID = serverid;
        connection.Start();
    }
    void Run()
    {
        while(true)
        {
            //do stuff here
        }
    }
}

now, there is the class i need to manage, here is how im calling it:

static void Main(string[] args)
{
    StartConnection(1);
    StartConnection(2);
    StartConnection(3);

    //etc
}
static void StartCOnnection(int serverid)
{
    Connection connect = new Connection();
    connect.Start(serverid);
}

i was origanally trying to do somthing like this:

foreach(Connection connect in Connection)
{
    if(connect.SERVERID == 2)
    {
        //destroy the thread, and class.
    }
}

but that gets the error " 'Connection' is a 'type' but is used like a 'variable' ", and i dont know how to do that destroy the thread and class part...

Summary: So what i basically need to do, is get a list of all the open Connetion class's, and be able to, based on the settings of the class be able to destroy it. how do i do this?

~code examples please

+1  A: 

The code in you Main() won't compile.

You need something like:

List<Connection> connections = new List<Connection> ();

Connection connect;

connect = new Connection();
connect.Start(1);
connections.Add(connect);

connect = new Connection();
connect.Start(2);
connections.Add(connect);

// etc

And then you can later do:

foreach(Connection connect in connections)
{
    if(connect.SERVERID == 2)
    {
        //destroy the thread, and class.
    }
}

For the actual stopping, I agree with SnOrfus' answer. You need to build in some logic to break the while-loop.

Henk Holterman
+3  A: 

You didn't say what kind of errors you're getting. That might help. Also; you might want to add a stop method on your connection that looks like:

public void Stop()
{
    if (this.connection.IsAlive)
    {
        this.stopCondition = true;
        this.connection.Join();
    }
}

where stopCondition is a class member that is checked in your while loop (instead of just 'true').

SnOrfus
+1: straightforward solution. Also make sure stopCondition is declared volatile and the loop in the run statement is written while(!stopCondition).
Juliet
@Juliet +1: I considered that a given, but for completeness you're absolutely correct.
SnOrfus