开发者

Getting and terminating class's/threads in C#

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


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').


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜