0

I'm trying to connect through the application I'm making as a client to my phone for testing purposes, but I'm missing something. After pairing the devices, the program should open a new thread on which it runs client.BeginConnect, but it only gets as far as "Starting connect thread...".

        BluetoothDeviceInfo deviceInfo;
    private void listBox1_DoubleClick(object sender, EventArgs e)
    {
        deviceInfo = devices.ElementAt(listBox1.SelectedIndex);
        updateUI(deviceInfo.DeviceName + " was selected. Attempting to connect.");

        if (pairDevice())
        {
            updateUI("Device paired.");
            updateUI("Starting connect thread...");
            Thread bluetoothClientThread = new Thread(new ThreadStart(ClientConnectThread));
        }
        else
        {
            updateUI("Pairing failed.");
        }
    }

    private void ClientConnectThread()
    {
        updateUI("Attempting connect.");
        client.BeginConnect(deviceInfo.DeviceAddress, BluetoothService.SerialPort, new AsyncCallback(BluetoothClientConnectCallback), client);
    }

I tried reusing a thread I used for scanning for devices previously and pasted the BeginConnect there, but that just makes the program crash. I'm unsure of what error it might show, because I'm programming it on my PC, but can only test the program on another laptop using the .exe file.

MrE
  • 3
  • 3

1 Answers1

0

You have created a thread, but you haven't asked it to start yet:

Thread bluetoothClientThread = new Thread(new ThreadStart(ClientConnectThread));
bluetoothClientThread.Start(); // <--- this starts the thread

See here for details

Of course, then you have another problem because you call BeginConnect (which is asynchronous) and then the function ends (and so will the thread).

Neil
  • 11,059
  • 3
  • 31
  • 56
  • Thank you, you truly hit the the nail on the head. I added the .Start and created a manual reset event so it pauses the thread until .Set is called from the callback, but the callback method still doesn't seem to be running any further. Unless I somehow botched the set event and it doesn't run at all. @Neil – MrE Jun 01 '18 at 06:39
  • I've no idea why it kept crashing when connecting to mu phone, but with the Arduino I was making it for it works, so I guess this is solved. – MrE Jun 01 '18 at 11:10