#Pragma DisableBackgroundTasks question

Hey gang,

I have a question on the #Pragma directive DisableBackgroundTasks.

I have a thread that has a loop. In each pass of the loop, the thread writes data to a serial port. Then it suspends itself before starting the next iteration. In the DataAvailable event of the serial port, I check to see if the data I am looking for has arrived yet. If not, I poll the socket and wait again. If all of my data has arrived, I process it and then I resume the thread. Also, if the thread is not suspended when the data arrives, I poll the socket and exit the event.

In OS X, this works wonderfully. In Windows, it seems like there are timing issues between when the thread suspends vs. when the data comes in, etc. It does not work so well.

However, if I put #Pragma DisableBackgroundTasks as the first line in my DataAvailable event, then everything seems to work just wonderfully on Windows as it does in OS X.

Is this a good idea to rely on the #Pragma directive to make things work right like this? Or is there some other fundamental flaw in my logic?

Thanks!

The “background events” that will be suspended are other threads, so you are stopping the other thread from processing while you handle the incoming. Depending on your code, that doesn’t seem like a bad idea.

But I wonder why you are relying on a thread for this at all? If your thread suspends after every iteration, it sounds like a better case for a Timer or even straight code. Is it taking that long to send the data?

I don’t know anything about serial ports, but all the DisableBackgroundTasks pragma disables is automatic thread yielding at loop boundaries in the current scope.

I also suggest to use timer.

I used a thread because I want this running in the background because I have other tasks going on at the same time. The time it takes to write the data itself is not long but there could be quite a few iterations of the loop. So there could be a lot of writes.

However, the timer approach is intriguing. I’m already processing the received data on the main thread in DataAvailable. I would need to keep track of what iteration I am on with some other counter variable as I wouldn’t be able to use a for/next loop but that’s not hard to do. I’ll look into this.

Also, don’t use this in a listbox CellDrawbackgroundPaint and CellTextPaint events because this can crash your app at random running Mac OS X 10.10

I discovered this because some users complained my app crashed at random. I never figured out why until I removed the Pragmas in those events. Crashes are gone.
Because this only happens in OSX10.10 I suspect this is an OS X issue.

I went to using a timer as you and Kem suggested. It works very smooth. I think this was a good idea…