Mike
Mike

Reputation: 1295

Why does background thread block GUI

I have a C# Winforms application that talks to a USB device through a vendor library. I run this interface with a background thread. During the vendor constructor, the entire Winforms application GUI is frozen. One core of the CPU is at 100%, but the other cores are idle. How do I determine what calls the vendor is making to block the GUI?

I run the background thread like this -

public HardwareInterfaceClass() {
    var hardwareThread = new Thread(HardwareInterfaceThread);
    hardwareThread.IsBackground = true;
    hardwareThread.Name = "USB Interface Communication";
    hardwareThread.Start();
    return
}


private void HardwareInterfaceThread() {

  var usbInterface = new USBInterfaceHardware(0);  // Takes 5 seconds and blocks GUI
  ...

}

Upvotes: 2

Views: 920

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70652

There is nothing at all in the code you posted that would block the UI thread. So there are two possibilities:

  1. There is something in the library code you are calling that is blocking the UI thread.
  2. The UI thread is not really blocked.

It's impossible to know for sure which is correct, though the first option would be very unusual, especially if you hadn't actually passed anything to the library code that would even tell it where your UI thread is (but not impossible…it could have logic internally that seeks out your UI thread and somehow messes with it).

If the second option is correct, then the UI could seem to be blocked, but simply not getting enough CPU. The fact that your other CPU cores are idle suggests this isn't the problem, but given how remote the first possibility is, it's worth at least considering.

If your background thread is taking CPU time away from the UI thread, then you can fix that by setting hardwareThread.Priority = ThreadPriority.BelowNormal;. Indeed, this is a good idea to do for any thread that spins consuming 100% of a core's CPU time.

There is, of course, a third possibility: in your own code, you have somehow caused the UI thread to be blocked while this background thread is working. But without a concise, complete code example it would be impossible to explain where that is. We can only look at the code you posted, and that code doesn't block the UI anywhere.

Upvotes: 2

Related Questions