Reputation: 1486
I would like to ask you why is my method StartReading is not triggered? I expected "test" text in console but nothing appeared.
public class Connection
{
public List<byte[]> ReadBuffer = new List<byte[]>();
TcpClient ClientLogin;
NetworkStream StreamLogin;
DataEncoder NetworkBufferLogin;
Thread ReadingThread;
public Connection()
{
ClientLogin = new TcpClient("127.0.0.1", 13000);
StreamLogin = ClientLogin.GetStream();
NetworkBufferLogin = new DataEncoder(StreamLogin);
ReadingThread = new Thread(StartReading);
}
private void StartReading()
{
while (true)
{
Console.WriteLine("test");
byte[] a = NetworkBufferLogin.ReceiveData();
ReadBuffer.Add(a);
}
}
}
and simple calling
class Program
{
static void Main(string[] args)
{
Connection test = new Connection();
Console.ReadKey();
}
}
Upvotes: 1
Views: 4175
Reputation: 11
You need invoke method "Start()".
ReadingThread = new Thread(StartReading);
ReadingThread.Start();
I also recommend doing the background tread.
ReadingThread = new Thread(StartReading) {IsBackground = true};
ReadingThread.Start();
this will help to avoid a freeze program upon completion of the main tread.
Upvotes: 1
Reputation: 26536
I am not a C# guru but I think you need to call Thread.Start()
:
public Connection()
{
ClientLogin = new TcpClient("127.0.0.1", 13000);
StreamLogin = ClientLogin.GetStream();
NetworkBufferLogin = new DataEncoder(StreamLogin);
ReadingThread = new Thread(StartReading);
ReadingThread.Start();
}
Anyway, using a single thread for a single connection is a very bad idea. you should probably use asynchronous IO (which is remarkably simple and handy with TPL and async
/await
keywords, kudos, .Net), or at least use a threadpool.
you should think as your program as a business and creation of thread as hiring a new worker. would you hire and fire a whole new worker for each task your business requires? of course not. you should hire a few workers and make them work on the tasks that your business requires.
Upvotes: 9
Reputation: 172
ReadingThread = new Thread(StartReading);
ReadingThread.Start(); // to start your thread
ReadingThread.Stop(); // to stop your thread
ReadingThread.Sleep(2000); // to sleep(miliseconds) your thread
Upvotes: 0
Reputation: 5940
You forgot to start the thread:
public Connection()
{
ClientLogin = new TcpClient("127.0.0.1", 13000);
StreamLogin = ClientLogin.GetStream();
NetworkBufferLogin = new DataEncoder(StreamLogin);
ReadingThread = new Thread(StartReading);
ReadingThread.Start(); // <- here
}
Upvotes: 1