1

I'm developing a client-server program. I use C# programming language and .net framework 4. At there, whenever new client is connected to the server, the server will create new thread to process each client. If one of the client is disconnected, the thread which controls this disconnected client will also be stopped (killed). I don't know how to stop this specific thread among multiple threads. The pseudo-code of my program will be like that:

Server Side Program:

Thread t;
private void form1_load(object sender, EventArgs e)
{
    startserver();
}

void startserver()
{
     t = new Thread(waitclientconnection);
     t.start();
}

void waitclientconnection()
{
    //namedpipeserverconnection code
    //waitforclientconnection

    if (clientOne is connected)
    {    
         startserver(); //create new thread to wait connection for next client
    }

    //object and variable that created within the thread
    Clientprofile cp = new Clientprofile(); 
    String clientstate = "....";

    if (clientOne sends "close" message)
    {
    //the thread that controls ClientOne will be killed   <-- This is the point that I would like to solve
    }
}

I confessed that the program is a little complex but currently I have only this way to implement my program. I found some solutions that suggested to declare Boolean variable to control the thread stop or running using while looping. But in my program, this way can stop the whole thread and cannot able to create new threads for new connected clients. Moreover, I also want to know whether the variables and objects created in each specific thread can also be destroy from the memory when this thread is stopped. Imagine that if hundred clients were connected within one hour and currently only 10 clients are in connection. I only want to keep only objects and variables in memory for only these 10 clients. The question is complex but I'm sure all of you can able to solve and give any suggestions. Really hope for your suggestions...

4

2 に答える 2

1

接続を取得したときにクライアント スレッドを生成する単一のリスナー スレッドを持つように、コードをリファクタリングしてみてください。これらの各クライアント スレッドは、適切なタイミングで終了できる必要があります。また、サーバーの終了を妨げないように、クライアント スレッドのIsBackgroundプロパティを に設定する必要があります。true

あなたが現在行っている方法もおそらく実行可能ですが、必要以上に複雑に思えます。

于 2012-08-06T14:05:57.370 に答える
1

閉じるメッセージを受け取るスレッドは、「殺される」べきスレッドですよね?

したがって、コードが停止して正常に戻ることを確認してください。混乱を招くような
電話などはしないでください。Thread.Abort()

void waitclientconnection()
{
    if (clientOne is connected)
    {    
         startserver(); //create new thread to wait connection for next client
    }

    while (keepGoing)
    {
        ...

        if (clientOne sends "close" message)
        {
             keepGoing = false;
        }
    }
}
于 2012-08-06T14:03:02.157 に答える