I'm creating a game in which I use TCP/IP connection. The problem is that I'm using .Invoke to help me receive and send message.
The program goes like this: I'm my first window, i'm starting and connecting to the server like this :
{
TcpListener listener = new TcpListener(IPAddress.Any, this.port);
listener.Start();
try {
this.client = listener.AcceptTcpClient();
gameWindow = new GameWindow(this.client, true);
gameWindow.StartGame();
}
}
then i'm connecting to it like this:
{
IPEndPoint ipEnd = new IPEndPoint(this.serverIP, this.port);
{
try {
client.Connect(ipEnd);
if (client.Connected) {
gameWindow = new GameWindow(this.client, false);
gameWindow.StartGame();
}
}
}
The constructor for gameWindow (which is a form) looks like this:
public GameWindow(TcpClient thisClient, bool isServer)
{
InitializeComponent();
this.client = thisClient;
this.reader = new StreamReader(thisClient.GetStream());
this.writer = new StreamWriter(thisClient.GetStream());
this.writer.AutoFlush = true;
}
I must wait for the server to send a message to the client, and then start the client ( I have a function .startGame() that uses .ShowDialog() and creates some pictureBoxs)
But nowhere I can get my handle created. I've tried to put this.createHandle() (read about it here) into GameWindow_Load but still not works. If I try to send a message with:
workerSendData.RunWorkerAsync(); I get:
Additional information: Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
What can I do to get my handler created? Using Thread.Sleep will sleep my whole UI, which does not work (a "solution" found on the internet)
My code for sending message :
private void workerSendData_DoWork(object sender, DoWorkEventArgs e)
{
if (client.Connected) {
this.writer.WriteLine(this.toSend); // aici trimitem datele.
// de modificat : aici vom adauga in lista noastra miscarile.
this.Invoke(new MethodInvoker(delegate () { MessageBox.Show("Me:" + this.toSend + "\n"); }));
}
else {
MessageBox.Show("Send failed");
}
workerSendData.CancelAsync();
}
My code for receiving data:
private void workerReceiveData_DoWork(object sender, DoWorkEventArgs e)
{
while (client.Connected) {
try {
this.received = this.reader.ReadLine();
this.myTurn = true;
this.Invoke(new MethodInvoker(delegate () {
MessageBox.Show("This has been received: " + this.received);
/*this.tbReceive.AppendText("You:" + this.received + "\n");*/
}));
this.received = "";
}
catch (Exception x) {
MessageBox.Show(x.Message.ToString());
}
}
}
It seems that you cannot invoke an action before the Window is fully initialized and loaded. Assuming you are working in Windows Forms, there is a solution provided by #Greg D on this question, but it doesn't be to be the safest way to go.
I would suggest that you try to find a way to start the worker only after the window is loaded (for example using the Loaded event), so that the handle is definitely ready and this situation does not occur.
Related
I read/write data to serial port and I want to see reading on listbox right away. I created a new thread to send command to serial port. I keep the main thread empty, so, it can update the UI and also serial port event handler wont be interrupted with something else.(I am not sure is it right approach?)
The following code works with while (!dataRecieved) { Thread.Sleep(4000); } but does not works with while (!dataRecieved) { Thread.Sleep(100); }.
The problem is if I use 100ms sleep, serial port event handler fire only once and then program stops!(If I debug with breakpoint 100ms works because I create additional time when stepping into the code.) If I wait 4000ms the program works. Also, I check the time between sending data and receiving data from serial port is 200ms. So, 100ms is reasonable.
Here is the code:
public bool dataRecieved = false;
public Form1()
{
InitializeComponent();
}
public void AppendTextBox(string value)
{
this.Invoke((MethodInvoker)delegate { richTextBox1.Text += value + "\n";});
}
private void button1_Click(object sender, EventArgs e)
{
serialPort1.Open();
Thread testThread = new Thread(() => sendThread());
testThread.Start();
}
public void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
data = serialPort1.ReadLine();
dataRecieved = true;
}
public void sendThread()
{
for(int i = 0; i<10; i++)
{
serialPort1.WriteLine("AT" + i);
// Following line creates odd situation:
// if Thread.Sleep(100), I receive only first data, then program stops(serial port handler doesnt fire!).
// if Thread.Sleep(4000), I receive all data, successfuly works.
// But I do not want to wait 4000ms, because I receive answer from device in 200ms.
while (!dataRecieved) { Thread.Sleep(100); }
AppendTextBox("Received" + "AT" + i);
dataRecieved = false;
}
}
Where I am wrong? Can you please provide a solution?
I even didn't use a new Thead for write and read on SerialPort. You just need use update control in Invoke() is ok. Below is my update on richTextBox. You can change form richTextBox to your listbox.
public void update_RichTextBox(string message)
{
Invoke(new System.Action(() =>
{
txtReceivedData.Text += message;
txtReceivedData.Refresh();
txtReceivedData.SelectionStart = txtReceivedData.Text.Length;
txtReceivedData.ScrollToCaret();
}));
}
and the way to use above void:
if (ComPort.IsOpen)
{
ComPort.Write(_inputdata + "\r");
Form1._Form1.update_RichTextBox(_inputdata + "\r");
string _receviedData = ComPort.ReadExisting();
Form1._Form1.update_RichTextBox(respond);
ComPort.DiscardInBuffer();//delete all data in device's received buffer
ComPort.DiscardOutBuffer();// delete all data in transmit buffer
}
else
{
MessageBox.Show("haven't yet open COM port");
return "FLASE";
}
I use something I call "Cross Thread Linker"
#region Cross Thread Linker
public bool ControlInvokeRequired(Control c, Action a)
{
if (c.InvokeRequired) c.Invoke(new MethodInvoker(delegate { a(); }));
else return false;
return true;
}
void Update_RichTextBox(RichTextBox rtb, string Text)
{
if (ControlInvokeRequired(rtb, () => Update_RichTextBox(rtb, Text))) return;
rtb.AppendText(Text + Environment.NewLine);
}
#endregion
Then:
Update_RichTextBox(richTextBox1, "Text to append");
I tested this code with placing a breakpoint in Monodevelop, running on a Raspbian. This app needs to communicate with a Windows, with a C# console application.
Although the timer1_Tick method prints the incoming message everytime (and it clearly prints the new message, because there I clear the message variable everytime after an incoming message), it seems to be that the OnNewData doesn't run everytime, when there's an incoming message.
I ask new incoming message with sending the "mes" out in the timer1_Tick.
I don't process the other kind of incoming messages in that method, but for the response for "mes", this place would be the best for processing. The reason is the "mes" creates answer types ("", " type answers), what I can get anytime.
I don't know what is the problem. Any idea? How could this happen, if the textbox is being refreshed nicely after each new incoming message?
public partial class Form0 : Form
{
public static string ReadCharactersIntoString(){
char c='c';
string outputString=String.Empty;
do{
c=(char)streamReader.Read();
outputString=outputString+c;
}while(c!='>');
return outputString;
}
async void OnNewData(object sender, EventArgs e){
message = Form0.ReadCharactersIntoString ();
//work with message variable works unreliable...
//sometimes this method runs, when there's an incoming message, sometimes it's not...
//although tick method prints the message everytime...
//why? how to solve this?
reseter.Set ();
}
public void AcceptMessages(){
while (true) {
try{
if (streamReader!=null && streamReader.Peek () > 0) {
newIncomingDataEvent.Invoke(this,EventArgs.Empty);
reseter.WaitOne ();
}
}catch{
}
}
}
public static async Task Waiting(){
while (message == null || message[message.Length-1]!='>') {
}
}
public static async Task<string> CollectingAnswer(){
await Waiting();
return message;
//when the answer is completely collected, it gives me back
}
public void ConnectionEstablisher()
{
while (true)
{
if (!activeConnection)
{
try
{
socketForServer = new TcpClient(ip, port);
networkStream = socketForServer.GetStream();
streamReader = new System.IO.StreamReader(networkStream);
streamWriter = new System.IO.StreamWriter(networkStream);
streamReader.BaseStream.ReadTimeout = 5000;
streamWriter.BaseStream.ReadTimeout = 5000;
activeConnection = true;
newIncomingDataEvent+=OnNewData;
reseter = new ManualResetEvent (true);
}
catch(Exception e)
{
activeConnection = false;
}
}
}
}
private async void timer1_Tick(object sender, EventArgs e)
{
if (this.Visible && activeConnection)
{
try
{
streamWriter.Write("mes");
streamWriter.Flush();
textBoxSending.AppendText("mes" + Environment.NewLine);
collectAnswer=CollectingAnswer();
outputString=await collectAnswer;
message=null;
textBoxAccepting.AppendText(outputString + Environment.NewLine);
//this always prints the incoming response message...
i do have an embedded board (mini/tiny 210)
and i did try building an application which uses system.socket and system.socket.net in C# ( vs2005 - wince5 device application but i do have wince 6 on my device!! )
my purpose is to send and receive data bytes using Ethernet. for sending , well there is no problem but receive does need multitasking.
i should start a task so it can listen to the port if there is any data upcoming but once i add thread part to my code the whole program crashes (dose not do that in pc x64 core i5) but in embedded board it will crash.
if i eliminate multi tasking i might lose some data when networkstream.read is not online or when networkstream.read is online and i'm waiting for data,which ends in program will not respond up until the timeout. here is some of my codes . hope it helps.
this code does work :
private void button_connect_Click(object sender, EventArgs e)
{
try
{
//Thread TH = new Thread(new ThreadStart(con));
//TH.Start();
con();
}
catch
{
MessageBox.Show("THREAD ERROR");
}
}
public void con()
{
try
{
cli = null;
cli = new TcpClient();
cli.Connect(IPAddress.Parse(textBox_ip.Text),Convert.ToInt32(textBox_port.Text));
st = null;
st = cli.GetStream();
button_connect.Enabled = false;
button_Close.Enabled = false;
button_disconnect.Enabled = true;
statusBar1.Text = "Connected to server";
//Thread rec = new Thread(new ThreadStart(recf));
//rec.Start();
}
catch
{
MessageBox.Show("Connection faild","Error");
statusBar1.Text = "Faild to connect to server";
}
this code dose not work :
private void button_connect_Click(object sender, EventArgs e)
{
try
{
Thread TH = new Thread(new ThreadStart(con));
TH.Start();
//con();
}
catch
{
MessageBox.Show("THREAD ERROR");
}
}
public void con()
{
try
{
cli = null;
cli = new TcpClient();
cli.Connect(IPAddress.Parse(textBox_ip.Text),Convert.ToInt32(textBox_port.Text));
st = null;
st = cli.GetStream();
button_connect.Enabled = false;
button_Close.Enabled = false;
button_disconnect.Enabled = true;
statusBar1.Text = "Connected to server";
//Thread rec = new Thread(new ThreadStart(recf));
//rec.Start();
}
catch
{
MessageBox.Show("Connection faild","Error");
statusBar1.Text = "Faild to connect to server";
}
}
as you can see i'm getting this crash while just one of my task is in the code the second task has been commented
i appreciate your help in advance
The crash is probably caused by updating UI elements from a secondary thread.
The con method reads a textbox and updates several buttons as well as a status bar, and this should only happen on the main application thread.
To verify whether this is the issue, you could simply comment out the lines in the con method that access UI elements (copy the textbox value to a member string before starting the thread, or just hard-code the IP address) and re-run the application.
Then to actually fix the problem you'll have to look into Control.Invoke.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
In the below code, I am getting null reference exception I didn't understand why I am getting that. Please help me to solve it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Data.SqlClient;
using System.Configuration;
namespace TCPListener
{
public partial class Form1 : Form
{
// Declare our worker thread
private Thread workerThread = null;
public Form1()
{
InitializeComponent();
// Initialise and start worker thread
this.workerThread = new Thread(new ThreadStart(this.ReceiveTcpData));
this.workerThread.Start();
}
public void timer1_Tick(object sender, EventArgs e)
{
}
public TcpListener server = null;
public Int32 port = Convert.ToInt32(ConfigurationManager.AppSettings["PUERTO"].ToString());
public IPAddress localAddr = IPAddress.Parse(ConfigurationManager.AppSettings["IP"].ToString());
public void OpenSocket()
{
try
{
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
}
catch (SocketException e)
{
Common.CommonControls.writeToLogFile("SOCKET ERROR: " + e.Message);
}
finally
{
Common.CommonControls.writeToLogFile("INICIO DE ESCUCHA EN " + DateTime.Now);
}
}
private void ReceiveTcpData()
{
//Instancio los objetos
Entities.Program oPosiciones = new Entities.Program();
DataAccess.Program oPosicionesDA = new DataAccess.Program();
try
{
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
//TcpClient client = server.AcceptTcpClient();
TcpClient cliente = new TcpClient();
try
{
cliente = server.AcceptTcpClient();
}
catch (Exception e) { MessageBox.Show(e.ToString()); }
data = null;
// Get a stream object for reading and writing
NetworkStream stream = cliente.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
// Process the data sent by the client.
data = data.ToUpper();
if (data.Substring(0, 2) == "##")
{
//SalidaMonitor("Paquete recibido: LOGON REQUEST del equipo");
cliente.Close();
this.workerThread.Interrupt();
return;
}
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
//Show data on monitor
SalidaMonitor("Paquete recibido " + DateTime.Now + ": " + data);
//Declare entities
oPosiciones.Paquete = data;
//Database action
oPosicionesDA.InsertarPosiciones(oPosiciones);
// Send back a response.
//stream.Write(msg, 0, msg.Length);
//SalidaMonitor("Paquete enviado: " + msg);
}
// Shutdown and end connection
cliente.Close();
}
catch (SocketException e)
{
Common.CommonControls.writeToLogFile("SOCKET ERROR: " + e.Message);
}
catch (SqlException x)
{
Common.CommonControls.writeToLogFile("SQL ERROR: " + x.Message);
}
catch (Exception y)
{
Common.CommonControls.writeToLogFile("ERROR: " + y.Message);
}
finally
{
oPosiciones = null;
oPosicionesDA = null;
this.workerThread.Interrupt();
}
}
private void SalidaMonitor(string data)
{
lstMensajes.Invoke(new MethodInvoker(delegate { lstMensajes.Items.Add(data.ToString()); }));
lstMensajes.Invoke(new MethodInvoker(delegate { lstMensajes.SelectedIndex = lstMensajes.Items.Count - 1; lstMensajes.SelectedIndex = -1; }));
}
private void Form1_Load(object sender, EventArgs e)
{
OpenSocket();
}
private void Form1_Close(object sender, FormClosingEventArgs e)
{
server.Stop();
}
}
}
In the above code, I am getting error at cliente = server.AcceptTcpClient();. I don't understand why it's happening. If you need any information, let me know. Thanks
The Problem
in the constructor of the form you are creating and starting new Thread.
and this thread will call the ReceiveTcpData method, which user the server variable (and at this point this variable was not initialized yet) WHY??
because the server variable is initialized in the Form_Load which call the OpenSocket method to initalize the server variable. The most important part is The Form_Load method is called AFTER the constructor of the form.
In other words, the Thread is using the server variable before you initialize it.
The Solution
use the following constructor, and remove the Form_Load event handler
public Form1()
{
InitializeComponent();
// add this line.
OpenSocket();
// Initialise and start worker thread
this.workerThread = new Thread(new ThreadStart(this.ReceiveTcpData));
this.workerThread.Start();
}
Update
For the person who prefer to do everything in the Form_Load
here is another solution
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// add this line.
OpenSocket();
// Initialise and start worker thread
this.workerThread = new Thread(new ThreadStart(this.ReceiveTcpData));
this.workerThread.Start();
}
Well, if it is in that line, it is because server is not initialized.
Ok, so I'm attempting to create a simple Chat application over TCP/IP for a group of friends of mine who play DnD online. Eventually I want to add more features, but for now I just want the chat to work!!
Here is the code I have for the Main Server
class MainServer
{
IPAddress m_address = IPAddress.Parse("127.0.0.1");
Int32 m_port = 5550;
public static Hashtable userNicknames = new Hashtable(50);
public static Hashtable connectionToNick = new Hashtable(50);
public MainServer()
{
TcpListener listener = new TcpListener(m_address, m_port);
Thread listenThread = new Thread(new ParameterizedThreadStart(StartListening));
listenThread.Start(listener);
Console.WriteLine("Listening for incoming connection requests...");
}
private void StartListening(Object listener)
{
TcpListener server = (TcpListener)listener;
ClientCommCenter commC;
server.Start();
while (true)
{
if (server.Pending())
{
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Client has connected...");
commC = new ClientCommCenter(client);
}
}
}
public static void SendSystemMessage(string msg)
{
StreamWriter writer;
TcpClient[] connectedClients = new TcpClient[MainServer.userNicknames.Count];
MainServer.userNicknames.Values.CopyTo(connectedClients, 0);
for (int ii = 0; ii < connectedClients.Length; ii++)
{
try
{
if (msg.Trim().Equals(String.Empty))
continue;
writer = new StreamWriter(connectedClients[ii].GetStream());
writer.WriteLine("Message from server: " + msg);
writer.Flush();
writer = null;
}
catch (Exception e)
{
MainServer.userNicknames.Remove(MainServer.connectionToNick[connectedClients[ii]]);
MainServer.connectionToNick.Remove(connectedClients[ii]);
}
}
}
public static void SendMessageToAll(string nickname, string msg)
{
StreamWriter writer;
TcpClient[] connectedClients = new TcpClient[MainServer.userNicknames.Count];
MainServer.userNicknames.Values.CopyTo(connectedClients, 0);
for (int ii = 0; ii < connectedClients.Length; ii++)
{
try
{
if (msg.Trim().Equals(String.Empty))
continue;
writer = new StreamWriter(connectedClients[ii].GetStream());
writer.WriteLine(nickname + ": " + msg);
writer.Flush();
writer = null;
}
catch (Exception e)
{
String user = (string)MainServer.connectionToNick[connectedClients[ii]];
SendSystemMessage("ATTENTION: " + user + " has disconnected from chat");
MainServer.userNicknames.Remove(user);
MainServer.connectionToNick.Remove(connectedClients[ii]);
}
}
}
}
Here is the main communication class, used separately by each client
class ClientCommCenter
{
TcpClient m_client;
StreamReader m_reader;
StreamWriter m_writer;
String m_nickname;
public ClientCommCenter(TcpClient client)
{
m_client = client;
Thread chatThread = new Thread(new ThreadStart(StartChat));
chatThread.Start();
}
private String GetNick()
{
m_writer.WriteLine("Enter a nickname to begin.");
m_writer.Flush();
return m_reader.ReadLine();
}
private void StartChat()
{
m_reader = new StreamReader(m_client.GetStream());
m_writer = new StreamWriter(m_client.GetStream());
m_writer.WriteLine("Connected to DnD Chat!!");
m_nickname = GetNick();
while (MainServer.userNicknames.Contains(m_nickname))
{
m_writer.WriteLine("ERROR!!! Username already in use");
m_nickname = GetNick();
}
MainServer.userNicknames.Add(m_nickname, m_client);
MainServer.connectionToNick.Add(m_client, m_nickname);
MainServer.SendSystemMessage("****** " + m_nickname + " ****** has joined the chat!");
m_writer.WriteLine("Now connected....");
m_writer.Flush();
Thread startChatting = new Thread(new ThreadStart(runChat));
startChatting.Start();
}
private void runChat()
{
try
{
String clientMessage = String.Empty;
while(true){
clientMessage = m_reader.ReadLine();
MainServer.SendMessageToAll(m_nickname, clientMessage);
}
}
catch(Exception e)
{
Console.WriteLine(e);
}
}
}
And finally, here is the code for the Client class:
public partial class MainForm : Form
{
[DllImport("kernel32.dll")]
private static extern void ExitProcess(int a);
TcpClient client;
StreamReader m_reader;
StreamWriter m_writer;
public MainForm()
{
InitializeComponent();
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = false;
Application.Exit();
if (m_reader != null)
{
m_reader.Dispose();
}
ExitProcess(0);
}
private void MainForm_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
SendChat();
}
}
private void SendChat()
{
TextBox txtChat = (TextBox)chatEntry;
if (chatEntry.Lines.Length >= 1)
{
m_writer.WriteLine(txtChat.Text);
m_writer.Flush();
chatEntry.Text = String.Empty;
chatEntry.Lines = null;
}
}
private void RunChat()
{
StreamReader reader = new StreamReader(client.GetStream());
while (true)
{
Application.DoEvents();
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker( delegate{
RunChat();
}));
}
if (reader.Peek() > 0)
{
chatDisplay.AppendText(reader.ReadLine() + "\r\n");
chatDisplay.SelectionStart = chatDisplay.Text.Length;
}
}
}
private void toolstripConnectButton_Click(object sender, EventArgs e)
{
client = new TcpClient("127.0.0.1", 5550);
m_writer = new StreamWriter(client.GetStream());
m_reader = new StreamReader(client.GetStream());
Thread chatThread = new Thread(new ThreadStart(RunChat));
chatThread.Start();
while (true)
{
Application.DoEvents();
}
}
private void sendButton_Click(object sender, EventArgs e)
{
SendChat();
}
}
The problem that I am having with the above code is this: I can connect to the running server perfectly fine, and I am correctly prompted by the server that I have connected, and it then prompts me for a nickname.
I type the nickname into the text box and press send. After this occurs however, I stop receiving messages from the server all together. Literally nothing. I can even spam the connect button and it constantly shows up with the same two messages:
"Connected"
"Enter a nickname"
I have been trying to figure this out for close to 5 hours now, and I simply have no idea what is going on. I have a feeling it is something incredibly simple, as the solution is ALWAYS simple.
So, generous people of SO, can you figure out my problem? Why does my streamreader and streamwriter suddenly stop working?!?!?!
Two things:
First, skip the if (reader.Peek() > 0). Just call reader.ReadLine(); this will block until you have a line available. I am not sure why, but even after sending the message, Peek is returning -1, but ReadLine returns a line at that point, fixing the problem. Anyway, spinning around on Application.DoEvents() is not helping matters.
(Similarly, you can skip if (server.Pending())).
Second, your use of Invoke is faulty; you should not be "Invoking" RunChat() because that is the method that repeatedly polls the stream for new data. This means you will run the entire method on the UI thread, which is precisely what you want to avoid. The UI is busy pumping the Windows message queue. You should "Invoke" only the code that modifies the control's properties.
(I suspect that is why you found it necessary to use Application.DoEvents() anyway. You shouldn't need it if you are handling your threading correctly.)
(Also, the first thing you should do is to check InvokeRequired. As your method is now, you're creating a StreamReader that you can never use. There are other places where you do that, but that's off topic.)
Here are two suggestions:
private void RunChat()
{
StreamReader reader = new StreamReader(client.GetStream());
Delegate invoker = new Action<string>(AppendChatText);
while (true)
Invoke(invoker, reader.ReadLine());
}
or, to use the more classic "invoke" pattern:
private void RunChat()
{
StreamReader reader = new StreamReader(client.GetStream());
while (true)
AppendChatText(reader.ReadLine());
}
private void AppendChatText(string text)
{
if (this.InvokeRequired)
{
this.Invoke((Action<string>)AppendChatText, text);
return;
}
chatDisplay.AppendText(text + "\r\n");
chatDisplay.SelectionStart = chatDisplay.Text.Length;
}
The first has the advantage of creating only one Delegate object; the second creates a new one each time.
Finally, this is a very C# 1.2 approach to the problem. A more up-to-date approach would use async/await to avoid creating all those threads (not to mention System.Collections.Generic.Dictionary<,> instead of HashTable).