C#C
C#3y ago
Gibbo

✅ Can you lock or freeze a thread while using another form in a new thread??

Part of my application requires i detect a USB device, and grab the DeviceID, I've got this and works fine, how ever im trying to get it to open a new form when it detects that the device is connected. again i got this working.

the issue i got is i want it open a form and pass in a serial number from the USB. again i got this working but had to open the form by spawning a new thread. however dispite the form being open as Showdialog(), i can still access the main form. im assuming this is because they are on 2 separate threads. am i able to lock the previous thread while i have the new form open ??? and when it closes unlock it?

this is my code for opening the form currently
 private void DeviceInsertedEvent(object sender, EventArrivedEventArgs e)
        {
            // Update Interface to recognise USB inserted
            lblUSBDetection.Text = "-- USB Inserted";

            string serialNumber;

            // Retrieve Serial Number from USB Device
            ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];

            foreach (var s in instance.Properties)
            {
                //Output all properties and values to debug console window for testing
                //Debug.WriteLine(s.Name + " = " + s.Value);

                if (s.Name == "PNPDeviceID")
                {
                    string[] strings = s.Value.ToString().Split('\\');
                    serialNumber = strings[2];
                    Debug.WriteLine(serialNumber);
  
                    if (serialNumber != null)
                    {
                        //TODO if staement to show form  if Serial matches serial stored in the data base, for now open form for all USB devices
                        new Thread(() => new USBPopup(serialNumber).ShowDialog()).Start();
                    }
                    break;
                }
            }
        }
Was this page helpful?