开发者

How to construct a class in a new thread?

开发者 https://www.devze.com 2023-02-01 08:28 出处:网络
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

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 ClientH开发者_如何学编程andler(Socket cSocket, int cI)
    {
        _client = cSocket;
        InitSecurity();
        _pParser = new Parser(this);
        ClientIndex = cI;
    }

    //...
 }


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.


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.

0

精彩评论

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

关注公众号