lesderid
lesderid

Reputation: 3430

How to construct a class in a new thread?

How to construct a class in a new thread? I have a static class called Server and a non-static class called ClientHandler. I would like to run the constructor of a new ClientHandler instance in a new Thread. The constructor takes 2 arguments. I've tried multiple approaches but my process' thread count doesn't increase. A code snippet follows:

public static class Server
{
    //...

    public static void AcceptConnection(IAsyncResult iar)
    {
        var oldserver = (Socket) iar.AsyncState;
        var client = oldserver.EndAccept(iar);
        Console.WriteLine("Client [{0}] connected from {1}.", CHandlerIndex, client.RemoteEndPoint.ToString());

        new ClientHandler(client, CHandlerIndex); //This has to run in a new thread.

        CHandlerIndex++;
        ServerSocket.BeginAccept(new AsyncCallback(AcceptConnection), ServerSocket);
    }
}

public class ClientHandler
{
    private readonly Socket _client;
    private readonly Parser _pParser;
    public Security S;
    public int ClientIndex;

    //...

    public ClientHandler(Socket cSocket, int cI)
    {
        _client = cSocket;
        InitSecurity();
        _pParser = new Parser(this);
        ClientIndex = cI;
    }

    //...
 }

Upvotes: 0

Views: 4918

Answers (2)

Doobi
Doobi

Reputation: 4822

Async and Threaded are not synonymous. if you want a new thread create one explicitly using either a Threadpool, a raw "new thread(Threadstart...)" or look at using the new task parallel library.

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273824

Well, classes (objects) don't run on a specific thread. Only methods do. Your request, to run a constructor on another thread looks rather pointless. It would have no effect on where/how other methods run.

In the code you have given it looks like the new ClientHandler instance is unrooted, ie it could be Garbage collected.

Does ClientHandler have any other methods? They might be run on another thread.

Upvotes: 2

Related Questions