새 스레드에서 클래스를 생성하는 방법은 무엇입니까? Server라는 고정 클래스와 ClientHandler라는 비 정적 클래스가 있습니다. 새 Thread에서 새 ClientHandler 인스턴스의 생성자를 실행하고 싶습니다. 생성자는 2 개의 인수를 취합니다. 여러 접근법을 시도했지만 프로세스의 스레드 수가 증가하지 않습니다. 코드 스 니펫은 다음과 같습니다.새 스레드에서 클래스를 생성하는 방법은 무엇입니까?
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;
}
//...
}
왜 비동기식과 스레드식이 같지 않은가? 나는 그들이 그렇다고 말한 적이 없다. – lesderid
이것은 내 질문에 대한 직접적인 대답이 아닙니다. – lesderid
실제로, 스레드를 직접 생성하라는 두 가지 답변이 있습니다. 자습서가 있습니다. http://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx. 문제가 생성자 변수 인 경우 더 명확하게 질문하십시오. "ParameterizedThreadStart"를 사용하고 매개 변수를 래핑 할 클래스를 생성해야합니다 (객체 배열이 수행 할 것임). http://msdn.microsoft.com/en-us/library/system.threading.parameterizedthreadstart.aspx – Doobi