0

Hi Stack Overflow community,

I would like to append data from another thread to my richtextbox. I have written following code for this. It reads dongle information.

namespace MAXREFDES104 {
public partial class Form1 : Form
{
    IBleDongle dongle;

    List<ulong> bleAddresses = new List<ulong>();

    string comPort = "com4";
    public Form1()
    {
        InitializeComponent();
        Run(comPort);
    }

    public void Run(string comPort)
    {
        richTextBox1.AppendText("Connecting to dongle on " + comPort + "\n");
        dongle = new CySmartBleDongle(comPort);
        if (!dongle.Connect())
        {
            richTextBox1.AppendText("Error: Unable to connect to dongle at " + comPort + "\n");
            return;
        }
        richTextBox1.AppendText("Scanning for BLE Devices\n");
        bleAddresses.Clear();
        dongle.DeviceFound += OnDongleDeviceFound;
        dongle.StartScan();
    }

    private void OnDongleDeviceFound(object sender, BleDeviceEventArgs e)
    {
        if (e.Name.StartsWith("MAXREFDES104") && !bleAddresses.Contains(e.Address))
        {
            string txt = ("[" + bleAddresses.Count + "] " + e.Address.ToString("X02") + " Type: " + e.AddressType
                + " Power: " + e.Rssi + " Name: " + e.Name);
            SetText(txt.ToString());
            bleAddresses.Add(e.Address);
        }
    }

    public void SetText(string text)
    {
        if (InvokeRequired)
        {
            this.BeginInvoke(new Action<string>(SetText), new object[] { text });
            return;
        }
        this.richTextBox1.Text += text;
    }
}
}

The issue is it reads device on every other time e.g. it finds device as shown below:

enter image description here

then it could not:

enter image description here

Would it be possible to offer some comments on this one?

SONI
  • 19
  • 5
  • seems like [this question](https://stackoverflow.com/questions/303116/system-windows-threading-dispatcher-and-winforms) can be useful for you – ba-a-aton Aug 03 '21 at 10:15
  • 1
    Adding text part looks fine to me. Set breakpoint in `OnDongleDeviceFound` to see if event `DeviceFound` is rised. – Sinatr Aug 03 '21 at 10:27
  • 1
    Does this answer your question? [How do I update the GUI from another thread?](https://stackoverflow.com/questions/661561/how-do-i-update-the-gui-from-another-thread) and [How to access a WinForms control from another thread i.e. synchronize with the GUI thread?](https://stackoverflow.com/questions/58657831/how-to-access-a-winforms-control-from-another-thread-i-e-synchronize-with-the-g) –  Aug 03 '21 at 11:02

0 Answers0