Hi im very new to threads in general. Iam developing something like a Bluetooth Chat in c#. On the main form are 2 possibilities 1. updating the list of BT devices and connect to a device (Works fine) 2. Listen for devices connecting to the own BT chip.
for testing the BT functionality is disabled.
for #2 i created a thread after loading the form.
private void MainForm_Load(object sender, EventArgs e)
{
incomingConnectionThread = new Thread(checkForConnection);
incomingConnectionThread.Start();
}
public void checkForConnection()
{
while (listening) //boolean which is always true
{
if (cargui == null)
{
cargui = new sendReceiveForm(null);
cargui.ShowDialog();
}
}
}
because listening is always true a new form (new sendReceiveForm) is created and shown.
the new form contains another thread which is executed after the loading of the new form and has a loop which checks a stream if there is information received.
private void CarGui_Load(object sender, EventArgs e)
{
thread = new Thread(receiveData);
thread.Start();
}
private void receiveData()
{
while (listening)
{
try
{
if (stream.ReadByte() != -1)
{
if (rtfReceiveWindow.InvokeRequired)
{
rtfReceiveWindow.Invoke(new rtfDelegate(receiveData));
}
else
{
rtfReceiveWindow.Text += stream.ReadByte().ToString();
}
}
}
catch
{
}
}
}
The stream in the second form is the stream from a simple .txt streamReader with 1 digit. the second thread is stuck in an infinite loop (or seems so) and the app crashes. i have neither an idea where the problem is nor how i can fix it.
//EDIT
Updated the method to:
private void receiveData()
{
while (listening)
{
if (stream.ReadByte() != -1)
{
if (rtfReceiveWindow.InvokeRequired)
{
rtfReceiveWindow.Invoke(new rtfDelegate(receiveData));
}
else
{
rtfReceiveWindow.Text += stream.ReadByte().ToString();
}
}
}
}
but no difference
//EDIT2
The thing is it works fine until starting the 2 thread. if i comment the start of the 2 thread the form is created and seems to work fine.