Thread.Resume before Run() fails to run

I’ve got an app that will happily run with a background thread. I would like to suspend the background thread when it is not needed so it is not taking cpu cycles away from the main thread. To do this I have placed aThread.Suspend in the background thread at the point when it is finished. I’ve also placed aThread.Resume in the foreground task immediately before aThread.Run() invocation.

When I do this, the debugger halts at aThread.Run(), and unfortunately I can’t get an error message out of it to know why.

Any thoughts?

Most likely a Thread already running Message.

Try: If ThreadXYZ.State <> Thread.Running Then ...

(Written without access to a Dev. Machine…use with care…)

It’s not entirely clear, but I don’t think you can Resume() a thread that is not Running() - that doesn’t make sense to me and should be an error.

To see the error, in the debugger look for the runtime exception object. You can also mouse over the Bug icon and the tooltip should show the error. Are you not seeing those UI features?

Yes. The error is “You cannot call Run on a thread that is already running.”, which helps greatly. I’m very glad to learn about checking the Exception variable. It is exceedingly rare that I can see an error message by mousing over the Bug in the tool tip – and then for only a second before it disappears – for ANY break or exception. I don’t know why. I’m running 2016 R4.1

Not running Resume() on a thread that is running, makes good sense. I think I’ll need to place the Suspend() in the foreground task rather than the background task, and take advantage of the “ThreadXYZ.State <> Thread.Running” check as well.

Thanks!

Perhaps a better question to ask is this: After a background thread completes the code invoked by it’s Run() event, are any cpu cycles spent on it prior to the next Run() event occurring? If not, then there is no reason to even pursue this.

None - If the thread isn’t running, there’s no CPU processing with regard to the thread’s code.

Run and Resume are mutually exclusive. You should call one or the other, based on the state of the thread. Note that the thread could be in a state other than “Running”, such as “Sleeping” or “Waiting”. I would recommend something like

select case aThread.State
case "NotRunning"
     aThread.Run
case "Suspended"
     aThread.Resume
else
    // nothing to do here
end